Go-micro project combat six go-config

go-config

As you may have noticed, all the database connections and other things that needed to be configured in our previous projects were hardcoded in the code. This is not reasonable. So we introduce go-config in this section to solve this problem.

The official documentation of go-config says that it is a dynamic pluggable configuration library.

Use of go-config

1. Create a config.json file in the project root directory

{
  "mysql" : {
    "host" : "192.168.0.111",
    "port" : "3306",
    "user" : "mytestroot",
    "password" : "mytestroot",
    "database" : "shopping"
  }
}

2. modify main.go

Introduce go-config

import(
	...
	"github.com/micro/go-config"
	...
)

Referenced in the main func to
load the configuration file

err := config.LoadFile("./config.json")
if err != nil {
	log.Fatalf("Could not load config file: %s", err.Error())
	return
}
conf := config.Map()

Modify the database connection in the previous database.go

func CreateConnection(dbconf map[string]interface{}) (*gorm.DB, error) {
	host := dbconf["host"]
	port := dbconf["port"]
	user := dbconf["user"]
	dbName := dbconf["database"]
	password := dbconf["password"]
	return gorm.Open("mysql", fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",
		user, password, host, port, dbName,
	),
	)
}

Pass the configuration information in

//db
db, err := CreateConnection(conf["mysql"].(map[string]interface{}))
defer db.Close()

Summarize

There is nothing difficult about using go-config.
When golang represents json data, it usually uses map[string]interface{} to represent it. If the json structure is multi-dimensional, it is impossible to obtain the value through map[index1][index2]. It will fail to compile, prompting that interface{} is not a map. You can use forced transfer to convert interface to map[string]interface{}. Or you can use config.Get(...path) to get the final configuration value. The implementation of the Get method is also to loop the input path, and then each layer automatically converts the interface into a map[string]interface{} to adjust.

Guess you like

Origin blog.csdn.net/u013705066/article/details/89637598