go - 如何检查结构的特定属性是否为空?

标签 go

请原谅,我有 C# 背景!

我在 Go 中有以下结构。我们通过从文件中读取配置来填充此结构,效果很好。但是,我试图找到一种方法来判断结构中的特定属性在通过配置文件传入时是否为空。就像,明确地根本没有设置。

我为此苦苦挣扎了大约 3 个小时。我可以为类型字符串等执行此操作,但我无法找到如何在所有类型中通用地执行此操作?

package main

import (
    "encoding/json"
    "fmt"
    "os"
    "reflect"
)

// Config type for configuration
type Config struct {
    BatchSize  int    `json:"batchSize"`
    BatchTime  int    `json:"batchTime"`
    DataFolder string `json:"dataFolder"`
    TempFolder string `json:"tempFolder"`

    //Kafka configuration
    Brokers      []string `json:"streamBrokers"`
    TopicJoined  string   `json:"streamTopicJoined"`
    TopicRemoved string   `json:"streamTopicRemoved"`
    Group        string   `json:"streamGroup"`
    ClientName   string   `json:"streamClientName"`

    // Stats configuration
    StatsPrefix string `json:"statsPrefix"`

    //AWS S3 configuration
    AccessKey              string `json:"amazonAccessKey"`
    SecretKey              string `json:"amazonSecretKey"`
    Region                 string `json:"amazonRegion"`
    Endpoint               string `json:"amazonEndpoint"`
    S3Bucket               string `json:"amazonS3Bucket"`
    S3UploadBufferSize     int32  `json:"amazonS3UploadBufferSize"`
    S3UploadConcurrentSize int32  `json:"amazonS3UploadConcurrentSize"`
    S3UploadRetries        int32  `json:"amazonS3UploadRetries"`
    S3UploadRetryTime      int32  `json:"amazonS3UploadRetryTime"`

    //Logging
    StatsdHost string  `json:"statsdHost"`
    StatsdPort int     `json:"statsdPort"`
    StatsdRate float64 `json:"statsdRate"`

    //Test Publishing
    TestMode  bool `json:"testMode"`
    TestCount int  `json:"testCount"`
}

// LoadConfig load config from file
func LoadConfig(configFile string) *Config {
    if _, err := os.Stat(configFile); os.IsNotExist(err) {
        panic(err)
    }

    if config, err := loadFromFile(configFile); nil != err {
        panic(err)
    } else {
        fmt.Println("OneDrive", os.Getenv("OneDrive"))
        msValuePtr := reflect.ValueOf(config)
        msValue := msValuePtr.Elem()
        typeOfT := msValue.Type()

        for i := 0; i < msValue.NumField(); i++ {
            field := msValue.Field(i)
            // TODO: Check if field is null, regardless of type and the value from OS env variables...

        }
        return config
    }
}

func loadFromFile(path string) (*Config, error) {
    var config Config
    file, err := os.Open(path)
    if err != nil {
        return nil, fmt.Errorf("could not open config path %q: %v", path, err)
    }
    defer file.Close()

    decoder := json.NewDecoder(file)
    err = decoder.Decode(&config)
    if err != nil {
        return nil, fmt.Errorf("could not parse config path %q: %v", path, err)
    }
    return &config, nil
}

最佳答案

在 go 中,一个值的默认值是它的 zero value .您可能希望将所有类型设为指针(例如:*string 而不是 string),因为指针的零值为 nil。将您的配置文件解码为一个结构将保留缺少/具有 null 值的键的 nil 值。

请注意,由于 slice (例如:[]string)是引用类型,它们充当指针并且可以为空(这意味着您不需要将类型声明为 *[]字符串).

我过去曾使用这个库来帮助合并配置/设置所需的键(还有许多其他键): https://github.com/jinzhu/configor

编码/解码 json 的示例 - https://play.golang.org/p/DU_5Tuvm5-

关于go - 如何检查结构的特定属性是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46537040/

相关文章:

go - 执行模板到文件

go - ServeHTTP方法从哪里来

go - 为 golang 运行 GRPC 示例

pointers - golang如何用指针打印结构值

戈兰 : panic after mutex locks have been held for too long

input - Go - 如何知道输出 channel 何时完成

go - 函数不会返回多个返回 - 单值上下文中的多值

go - Systemd 未检测到 GOPATH(在没有二进制文件的情况下运行)

c++ - 有人试过在 Windows 上编译 Go 吗?它现在似乎支持生成 PE 格式的二进制文件

go - 在 Go 问题中获取 URL 参数