在 Go 中使用 viper 读取 bool 值

问题描述

我正在使用 viper 来管理 Go 应用的配置和环境变量。
所有值都来自 json 配置文件,期望 bool 值总是为假,即使它在 json 文件中具有真值

pyenv

配置包

{
  "database" : {
    "host" : "localhost","port": "3306"
  },"host": "localhost","port": ":3000","production": true,"cache": true
}

当我尝试访问任何字符串时,所有这些都是工作文件,但是当尝试访问 bool 变量时,它总是给出 false

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
}

解决方法

首先json标签写错了。

我认为 viper 不使用 json 标签。它使用 mapstructure 标签。 其他变量正在工作,因为变量的名称与映射到 json 标签上的名称相同。 (检查这个https://github.com/spf13/viper#unmarshaling

2 个解决方案:

首先:更改变量名称


type ViperConfig struct {
    Database struct {
        Host string `json:"host"`
        Port string `json:"port"`
    } `json:"database"`
    Host          string `json:"host"`
    Port          string `json:"port"`
    Production bool   `json:"production"`
    Cache      bool   `json:"cache"`
    TemplaCache   map[string]*template.Template
}

或者使用 mapstructure 标签



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" mapstructure:"production"`
    UseCache      bool   `json:"cache" mapstructure:"cache"`
    TemplaCache   map[string]*template.Template
}