处理服务配置的最佳方式是什么?

问题描述

我正在寻找在 Go 中读取大中型项目的配置文件的最佳方式。

  1. 哪个库适合读写配置文件
  2. 我应该以什么格式保存配置文件config.json.envconfig.yaml 或 ...)?

解决方法

在 Golang 中有很多方法可以处理配置。如果要处理 config.json,请查看 this answer。要处理环境变量,您可以使用 os 包,例如:

// 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"

您也可以使用 godotenv 包:

# .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")

查看this source了解更多信息。