Search code examples
goconfigurationarchitectureconfiguration-files

What is the best way to handle configuration of a service?


I'm looking for the best way to read config files on large and medium projects in Go.

  1. Which library is suitable for reading and writing config files?
  2. In what format should I save the config files (config.json or .env or config.yaml or ...)?

Solution

  • There are numerous way to handle the configuration in Golang. If you want to handle with config.json, then look at this answer. To handle with environment variables, you can use os package like:

    // Set Environment Variable
    os.Setenv("FOO", "foo")
    // Get Environment Variable
    foo := os.Getenv("FOO")
    // Unset Environment Variable
    os.Unsetenv("FOO")
    // Checking Environment Variable
    foo, ok := os.LookupEnv("FOO")
    if !ok {
      fmt.Println("FOO is not present")
    } else {
      fmt.Printf("FOO: %s\n", foo)
    }
    // Expand String Containing Environment Variable Using $var or ${var}
    fooString := os.ExpandEnv("foo${foo}or$foo") // "foofooorfoo"
    

    You can also use godotenv package:

    # .env file
    FOO=foo
    
    // main.go
    package main
    
    import (
      "fmt"
      "log"
      "os"
    
      "github.com/joho/godotenv"
    )
    
    func main() {
      // load .env file
      err := godotenv.Load(".env")
      if err != nil {
        log.Fatalf("Error loading .env file")
      }
      // Get Evironment Variable
      foo := os.Getenv("FOO")
    

    Look at this source for more.