golang里strcut存为toml文件的方法
背景
之前有介绍过在golang里如何读取toml文件文件,最近有个同学问我如何将struct存为toml文件,不过之前确实没这么操作过,所以就看了下toml的库的代码才找到方法。我采用的toml解析库为:github.com/BurntSushi/toml,在encode.go文件里的关键说明如下:
// NewEncoder returns a TOML encoder that encodes Go values to the io.Writer // given. By default, a single indentation level is 2 spaces. func NewEncoder(w io.Writer) *Encoder { return &Encoder{ w: bufio.NewWriter(w), Indent: " ", } } // Encode writes a TOML representation of the Go value to the underlying // io.Writer. If the value given cannot be encoded to a valid TOML document, // then an error is returned. // // The mapping between Go values and TOML values should be precisely the same // as for the Decode* functions. Similarly, the TextMarshaler interface is // supported by encoding the resulting bytes as strings. (If you want to write // arbitrary binary data then you will need to use something like base64 since // TOML does not have any binary types.) // // When encoding TOML hashes (i.e., Go maps or structs), keys without any // sub-hashes are encoded first. // // If a Go map is encoded, then its keys are sorted alphabetically for // deterministic output. More control over this behavior may be provided if // there is demand for it. // // Encoding Go values without a corresponding TOML representation---like map // types with non-string keys---will cause an error to be returned. Similarly // for mixed arrays/slices, arrays/slices with nil elements, embedded // non-struct types and nested slices containing maps or structs. // (e.g., [][]map[string]string is not allowed but []map[string]string is OK // and so is []map[string][]string.) func (enc *Encoder) Encode(v interface{}) error { rv := eindirect(reflect.ValueOf(v)) if err := enc.safeEncode(Key([]string{}), rv); err != nil { return err } return enc.w.Flush() }
关键代码
根据上面的说明可以写如下代码来实现此功能:
package main import ( "fmt" "os" "github.com/BurntSushi/toml" ) // Conf ... type Conf struct { Name string Age int } func main() { fileName := "/Users/5bug.wang/Desktop/test.toml" file, err := os.Create(fileName) if err != nil { fmt.Println(err) return } defer file.Close() encode := toml.NewEncoder(file) if err = encode.Encode(&Conf{Name: "5bug.wang", Age: 1}); err != nil { return } }