github.com/micro/go-micro/examples@v0.0.0-20210105173217-bf4ab679e18b/config/modify/modify.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  
     7  	"github.com/micro/go-micro/v2/config"
     8  	"github.com/micro/go-micro/v2/config/encoder/toml"
     9  	"github.com/micro/go-micro/v2/config/source"
    10  	"github.com/micro/go-micro/v2/config/source/file"
    11  )
    12  
    13  func main() {
    14  	// new toml encoder
    15  	t := toml.NewEncoder()
    16  
    17  	// create a new config
    18  	c, err := config.NewConfig(
    19  		config.WithSource(
    20  			// create a new file source
    21  			file.NewSource(
    22  				// path of file
    23  				file.WithPath("./example.conf"),
    24  				// specify the toml encoder
    25  				source.WithEncoder(t),
    26  			),
    27  		),
    28  	)
    29  	if err != nil {
    30  		fmt.Println(err)
    31  		return
    32  	}
    33  
    34  	// load the config
    35  	if err := c.Load(); err != nil {
    36  		fmt.Println(err)
    37  		return
    38  	}
    39  
    40  	// set a value
    41  	c.Set("foo", "bar")
    42  
    43  	// now the hacks begin
    44  	vals := c.Map()
    45  
    46  	// encode
    47  	v, err := t.Encode(vals)
    48  	if err != nil {
    49  		fmt.Println(err)
    50  		return
    51  	}
    52  
    53  	// write the file
    54  	if err := ioutil.WriteFile("./example.conf", v, 0644); err != nil {
    55  		fmt.Println(err)
    56  		return
    57  	}
    58  
    59  	fmt.Println("wrote update to example.conf")
    60  }