0

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 ...)?
kostix
  • 51,517
  • 14
  • 93
  • 176
  • 1
    This question seems to be opinion based. Could you identify any specific qualities you're looking for? – Hymns For Disco Apr 02 '21 at 08:23
  • Requests for libraries are off topic. The rest of your question is also entirely opinion based. In my opinion, for example: There's never any reason to use .env files. – Jonathan Hall Apr 02 '21 at 08:36
  • Hi! Unfortunately, there are multiple problems with your question: 1) It's [off-topic on SO](https://stackoverflow.com/help/on-topic) because it is not concerned with any problem related to programming; 2) You actually have multiple questions; 3) You seems to be preoccupied with the idea of using `.env` files for configuration—it's not bad but I would say they serve a purpose different from "general" configuration, and are not supposed to be read by the services themselves—but rather by whatever _starts_ these services. – kostix Apr 02 '21 at 08:41
  • …hence I would recommend to try using [different venues](https://github.com/golang/go/wiki#the-go-community) to ask your questions: the `r/golang` subreddit or the gopher's Slack channel or the Golangbridge forum—all should work w/o violating the on-topic rules; SO is just unfit for such open-ended/research/education-style questions. – kostix Apr 02 '21 at 08:42

1 Answers1

0

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.

Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231