the following program tries to Marshal a struct and write to file. The struct is nested and it contains toml tags. I am not receiving any error message and it seems correct. The print of the structure is ok. The output of the program is the following:
[]
{testServer {/var/www} {/tmp} [{testPolicy [10 20 30] [2 2 3]}]}
The created file is empty:
package main
import (
"fmt"
"io/ioutil"
"log"
"github.com/pelletier/go-toml/v2"
)
type source struct {
path string `toml:"path"`
}
type target struct {
path string `toml:"path"`
}
type policy struct {
policyName string `toml:"policyName"`
schemaDays []int `toml:"schemaDays"`
schemaCounts []int `toml:"schemaCounts"`
}
type servers struct {
serverName string `toml:"serverName"`
source source `toml:"source"`
target target `toml:"target"`
policies []policy `toml:"policies"`
}
func main() {
var s servers = createConfiguration()
b, err := toml.Marshal(s)
if err != nil {
log.Fatal(err)
}
fmt.Println(b)
err = ioutil.WriteFile("config.toml", b, 0644)
if err != nil {
panic(err)
}
fmt.Println(s)
}
func createConfiguration() (server servers) {
s := source{
path: "/var/www",
}
t := target{
path: "/tmp",
}
d := []int{10, 20, 30}
c := []int{2, 2, 3}
p := &policy{
policyName: "testPolicy",
schemaDays: d,
schemaCounts: c,
}
server = servers{
serverName: "testServer",
source: s,
target: t,
policies: []policy{*p},
}
return
}
Any good reason?
You should export the field of the struct:
The output will be:
See https://go.dev/play/p/49MrxpqZ8p5