pelletier / go-toml

Go library for the TOML file format
https://github.com/pelletier/go-toml
Other
1.68k stars 208 forks source link

Decode: improve errors on integers and strings #891

Closed pelletier closed 10 months ago

pelletier commented 10 months ago

Add struct field location and context to errors reported when trying to unmarshal a string or integer into an inappropriate Go type.

Given this program:

type Server struct {
        Path string
        Port int
}

type Cfg struct {
        Server Server
}

var cfg Cfg
data := `[server]
path = "/my/path"
port = "bad"`

file := strings.NewReader(data)
err := toml.NewDecoder(file).Decode(&cfg)
fmt.Println(err)
fmt.Println(err.(*toml.DecodeError).String()) // crashes on main

Output before patch:

toml: cannot store TOML string into a Go int

Output after patch:

toml: cannot decode TOML string into struct field toml_test.Server.Port of type int
1| [server]
2| path = "/my/path"
3| port = "bad"
 |        ~~~~~ cannot decode TOML string into struct field toml_test.Server.Port of type int

Based on https://github.com/pelletier/go-toml/pull/890