Home > other >  Parsing toml files does not always produce the expected results
Parsing toml files does not always produce the expected results

Time:08-10

This is source code: https://github.com/ivankf/stream-gen/blob/main/main.go#L1:L55

This is the toml file in the code: https://github.com/ivankf/stream-gen/blob/main/etc/sample.conf#L1:L21

I ran it more than ten times, and only two times returned the correct results:

➜  stream-gen git:(main) ✗ go run main.go       
startTime: 
➜  stream-gen git:(main) ✗ go run main.go
startTime: 
➜  stream-gen git:(main) ✗ go run main.go
startTime: 
➜  stream-gen git:(main) ✗ go run main.go
startTime: 
➜  stream-gen git:(main) ✗ go run main.go
startTime: 
➜  stream-gen git:(main) ✗ go run main.go
startTime: 
➜  stream-gen git:(main) ✗ go run main.go
startTime: 2022-01-01T00:00:00Z
➜  stream-gen git:(main) ✗ go run main.go
startTime: 
➜  stream-gen git:(main) ✗ go run main.go
startTime: 
➜  stream-gen git:(main) ✗ go run main.go
startTime: 2022-01-01T00:00:00Z
➜  stream-gen git:(main) ✗ go run main.go
startTime: 

environmental information:

Golang Version: go1.18.3 darwin/arm64

github.com/BurntSushi/toml v1.2.0

CodePudding user response:

You are getting following error for your code:

    (last key "influxdb.timeout"): incompatible types: TOML value has type string; destination has type integer
startTime: 

I tried with following struct for your Toml file and it worked without an issue.

type ConfigNew struct {
    Interval        string    `toml:"interval"`
    MetricBatchSize string    `toml:"metric-batch-size"`
    StartTime       time.Time `toml:"start-time"`
    EndTime         time.Time `toml:"end-time"`
    Format          string    `toml:"format"`
    Influxdb        struct {
        Urls            []string `toml:"urls"`
        Database        string   `toml:"database"`
        RetentionPolicy string   `toml:"retention-policy"`
        Timeout         string   `toml:"timeout"`
    } `toml:"influxdb"`
}

I used following Toml to go struct generator to generate the struct.

https://xuri.me/toml-to-go/

  • Related