0

I would like to get path to my sqlite DB from a config file. How could I do that in Go?

This is a code, which I wrote before:

database, _ := sql.Open("sqlite3", "C:\\Users\\username\\project\\source.db")

In this case my path is "hard coded" directly in code. I would like to set a variable, which takes a path from a config data.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Egor Kado
  • 13
  • 1
  • 3

1 Answers1

0

My first suggestion is that you use a JSON file rather than a YAML file for configuration, since Go supports it natively; you don't need to use any external packages.

type DBConfig struct {
    Path string `json:"path"`
}

func loadConfig(path string) (*DBConfig, error) {
    data, err := ioutil.ReadFile(path)
    if err != nil {
        return nil, err
    }

    var conf DBConfig
    err = json.Unmarshal(data, &conf)
    if err != nil {
        return nil, err
    }

    return &conf, nil   
}

My second suggestion is that you pass in the path to this config file in as a flag. You can supply a flag when you run your application like this:

$ go build . -o MyApp
$ ./MyApp --config=path/to/config/file

Flags are very powerful and allow you to easily configure your applications without changing much code. Using flags in Golang is simple.

var configPath = flag.String("config", "", "Path to file containing app config")

Just make sure that you add flag.Parse to the top of your main function in order to access them.

Here's a full example.

Good luck!

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Nick Corin
  • 2,214
  • 5
  • 25
  • 46
  • Go has excellent support for YAML, too. No reason to use JSON if you prefer YAML (and I generally do prefer YAML, or better, TOML, for configuration) – Jonathan Hall Nov 23 '19 at 18:27
  • Of course, you should go with what's best for your project and what you're most comfortable. But for the sake of simplicity, it's often handy to use what's build into the languages standard lib rather than relying on a third party lib. – Nick Corin Nov 23 '19 at 18:53