Created
January 30, 2017 22:31
-
-
Save nickcarenza/d847ec24455e70a8609b6602ed528133 to your computer and use it in GitHub Desktop.
Golang read connection details from my.cnf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 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
The function returns the same arguments it was called with, not the ones read from the ini file. Should it look like this?