小编典典

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

go

原谅我,我来自ac#背景!

我在Go中有以下结构。我们通过从文件中读取配置来填充此结构,效果很好。但是我试图找出一种方法来告诉结构中的某个特定属性(通过配置文件传递时是否为null)。如图所示,完全没有设置。

我为此奋斗了大约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
}

阅读 253

收藏
2020-07-02

共1个答案

小编典典

在执行过程中,值的默认值为其零值。您可能要使所有类型的指针成为指针(例如*string而不是string),因为指针的零值为nil。将配置文件解组到结构中将为丢失/具有空值的键保留nil值。

请注意,由于切片(例如:)[]string是引用类型,因此它们充当指针并且可以为空(这意味着您无需将类型声明为*[]string)。

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

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

2020-07-02