Skip to content

Instantly share code, notes, and snippets.

@nickcarenza
Created January 30, 2017 22:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickcarenza/d847ec24455e70a8609b6602ed528133 to your computer and use it in GitHub Desktop.
Save nickcarenza/d847ec24455e70a8609b6602ed528133 to your computer and use it in GitHub Desktop.
Golang read connection details from my.cnf
package db
// stdlib
import (
"fmt"
"os"
)
// external
import (
"github.com/go-ini/ini"
)
func MyCnf(profile string, host string, port string, dbname string, user string) (string, error) {
cfg, err := ini.LoadSources(ini.LoadOptions{AllowBooleanKeys: true}, os.Getenv("HOME")+"/.my.cnf")
if err != nil {
return "", err
}
for _, s := range cfg.Sections() {
if profile != "" && s.Name() != profile {
continue
}
if s.Key("host").String() != "" && s.Key("host").String() != host {
continue
}
if s.Key("port").String() != "" && s.Key("port").String() != port {
continue
}
if s.Key("dbname").String() != "" && s.Key("dbname").String() != dbname {
continue
}
if s.Key("user").String() != "" && s.Key("user").String() != user {
continue
}
var password = s.Key("password")
return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, password, host, port, dbname), nil
}
return "", fmt.Errorf("No matching entry found in ~/.my.cnf")
}
@shlomi-noach
Copy link

shlomi-noach commented Mar 1, 2021

The function returns the same arguments it was called with, not the ones read from the ini file. Should it look like this?

func MyCnf(profile string) (string, error) {
	cfg, err := ini.LoadSources(ini.LoadOptions{AllowBooleanKeys: true}, os.Getenv("HOME")+"/.my.cnf")
	if err != nil {
		return "", err
	}
	for _, s := range cfg.Sections() {
		if profile != "" && s.Name() != profile {
			continue
		}
		host := s.Key("host").String()
		port := s.Key("port").String()
		dbname := s.Key("dbname").String()
		user := s.Key("user").String()
		password := s.Key("password").String()
		return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s", user, password, host, port, dbname), nil
	}
	return "", fmt.Errorf("No matching entry found in ~/.my.cnf")
}

@nickcarenza
Copy link
Author

@shlomi-noach Your version looks correct for when you want to pull more that just the password from my.cnf, which is totally valid. Thanks for the post!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment