I'm looking for the best way to read config files on large and medium projects in Go.
config.json
or .env
or config.yaml
or ...)?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.