【问题标题】:What is the best way to handle configuration of a service? [closed]处理服务配置的最佳方式是什么? [关闭]
【发布时间】:2021-06-29 03:26:06
【问题描述】:

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

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

【问题讨论】:

  • 这个问题似乎是基于意见的。您能确定您正在寻找的任何特定品质吗?
  • 对库的请求与主题无关。您的问题的其余部分也完全基于意见。例如,在我看来:没有任何理由使用 .env 文件。
  • 嗨!不幸的是,您的问题存在多个问题:1)它是off-topic on SO,因为它不关心与编程相关的任何问题; 2)您实际上有多个问题; 3)您似乎全神贯注于使用.env 文件进行配置的想法——这还不错,但我想说它们的目的不同于“一般”配置,并且不应该被服务本身读取——但是而不是通过任何启动这些服务。
  • ...因此我建议尝试使用different venues 来提问:r/golang subreddit 或 gopher 的 Slack 频道或 Golangbridge 论坛——所有这些都应该在不违反主题的情况下工作规则; SO 不适合这种开放式/研究/教育式的问题。

标签: go configuration architecture config-files


【解决方案1】:

在 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 了解更多信息。

【讨论】:

    猜你喜欢
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    相关资源
    最近更新 更多