我正在使用 viper 来管理 Go app 的配置和环境变量。
json 配置文件中的所有值都是正确的,即使 bool 值在 json 文件中有一个 true 值,它也总是为 false
{
"database" : {
"host" : "localhost",
"port": "3306"
},
"host": "localhost",
"port": ":3000",
"production": true,
"cache": true
}
配置包
package config
import (
"github.com/spf13/viper"
"html/template"
"log"
)
type ViperConfig struct {
Database struct {
Host string "json:'host'"
Port string "json:'port'"
} "json:'database'"
Host string "json:'host'"
Port string "json:'port'"
ProductionMod bool "json:'production'"
UseCache bool "json:'cache'"
TemplaCache map[string]*template.Template
}
func LoadConfig(path string) (viperconfig ViperConfig, err error) {
viper.AddConfigPath(path)
viper.SetConfigName("config")
viper.SetConfigType("json")
viper.AutomaticEnv()
err = viper.ReadInConfig()
if err != nil {
log.Fatal("Can't load config file")
}
err = viper.Unmarshal(&viperconfig)
return
}
当我尝试访问任何字符串时,所有这些都是工作文件,但是当我尝试访问 bool 变量时,它总是给出 false
package main
import (
"github.com/alexedwards/scs/v2"
"github.com/fouad82/news-api/cmd/config"
"github.com/fouad82/news-api/cmd/routes"
"log"
"net/http"
"time"
)
func main() {
ViperConfig, err := config.LoadConfig("../")
if err != nil {
log.Fatal("Can't read viper configurations", err)
}
if err != nil {
log.Fatal("Error Parsing template", err)
}
session := scs.New()
session.Lifetime = 24 * time.Hour
session.Cookie.Persist = true
session.Cookie.SameSite = http.SameSiteLaxMode
session.Cookie.Secure = ViperConfig.ProductionMod
routes.Routes()
// the values never gives the actuall value it always gives false
log.Fatal(ViperConfig.UseCache, ViperConfig.ProductionMod)
http.ListenAndServe(ViperConfig.Port, nil)
}