Articles under category Golang

Recently, in the golang, which used all the online data in redis, the configuration that used to be written dead is not very suitable, and thermal loading is the kingly way.

As the saying goes, programmers who can't search are not good programmers.

I saw the other chiefs writing, mostly using. Timer +goroutine Achieved. It's not very difficult, starting code.

Configuration file structure

Let's assume that our configuration files are JSON files, which should be the following.

 / / conf.json
{
 "host": "127.0.0.1", "port": 6379, "passwd": "," "DB": 0
}

First of all, it must be to write a structure that is exactly the same as it.

 //json configuration file structure 
type Content struct {
Host string `json: "host" `
Port int `json: "`
Port", "" "," "" "

If it is not very safe to write operation functions on this structure, serialization of JSON is also a pointer to direct operation. The trial and error of breaking them up before, and finally let them stay together 233

Optimized structure

Integrate file name, synchronization lock, last modification time, and configuration file structure together.

 / / configuration structure 
type Config struct {
Filename string
LastModifyTime int64
Lock *sync.RWMutex
Data interface{}
}

Write the factory function of instance configuration (this is a conventional rule, the specific source is your own textual research, it has many advantages).

 Func NewConfig (filename string, data interface{}) *Config {
conf: = &Config{
Filename: filename, 
Data:, &Config{
Filename:, and (())

The default parameters are configured in the configuration structure, and the external parameter is File name of configuration file and Configuration file structure The type of data is interface type. The advantage is that Config Can be independent, code Multiple reuse We also used it. Conf.parse () Method, the first analytical file, Go conf.reload () Method to run a goroutine run alone (see the specific effect), and of course return to the ontology.

- reading the remainder part -

This page loaded in 0.000848 seconds