preface

Why use a configuration file?

  1. Centralized data management facilitates future maintenance
  2. Avoid hard coding and change content without recompiling

The target

  • go-iniThe use of
  • Adjust reading configuration file data

go-ini

features

  1. Support for overloading multiple data sources (file, []byte, IO.Reader and IO.ReadCloser)
  2. Recursive reading of key values is supported
  3. Reading parent and child partitions is supported
  4. Support reading from increment key names
  5. Supports reading multiple row key values
  6. Support for a large number of helper methods
  7. Supports direct conversion to the Go language type at read time
  8. Support for reading and writing annotations for partitions and keys
  9. Easily manipulate partitions, keys, and annotations
  10. Partitions and keys remain in the same order when saving the file

Download and install

go get gopkg.in/ini.v1
Copy the code

Read configuration file data

Added the INI configuration file

[server]
HTTP_PORT = :8888

[database]
TYPE = mysql
USER = root
PASSWORD =
#127.0.0.1:3306 Database IP: database port number
HOST = 127.0.0.1:3306
NAME = blog
Copy the code

New ConfigService

package ConfigService

import (
	"fmt"
	"gopkg.in/ini.v1"
	"os"
)

type DbInfo struct {
	TYPE         string
	USER         string
	PASSWORD     string
	HOST         string
	NAME         string
	HTTP_PORT    string
}

func GetAppConfig(key string) *DbInfo {
	cfg, err := ini.Load("Config/app.ini")
	iferr ! =nil {
		fmt.Printf("Fail to read file: %v", err)
		os.Exit(1)
	}
	d := new(DbInfo)
	_ = cfg.Section(key).MapTo(d)
	return d
}

func GetServerConfig(a) *DbInfo {
	return GetAppConfig("server")}func GetDbConfig(a) *DbInfo {
	return GetAppConfig("database")}Copy the code

The DbService connection string is adjusted to read configuration

package DbService

import (
	"fmt"
	"golang-blog/Model/Entity"
	"golang-blog/Service/ConfigService"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

var Db *gorm.DB

func ConnectDb(a) {
	var (
		err error
	)
	dbConfig := ConfigService.GetAppConfig("database")
	connectStr := fmt.Sprintf("%s:%s@tcp(%s)/%s? charset=utf8&parseTime=True&loc=Local", dbConfig.USER,
		dbConfig.PASSWORD,
		dbConfig.HOST, dbConfig.NAME)
	Db, err = gorm.Open(mysql.Open(connectStr), &gorm.Config{})
	iferr ! =nil {
		panic(err)
	}

	// Automatically generate the table structure
	dbErr := Db.AutoMigrate(&Entity.UserEntity{})
	ifdbErr ! =nil {
		println(err)
	}
}
Copy the code

The interface number of the Routers reads the configuration file

package Routers

import (
	"github.com/gin-gonic/gin"
	"golang-blog/Controller/HomeControoler"
	"golang-blog/Service/ConfigService"
)

func Init(router *gin.Engine) {
	home := router.Group("Home")

	// 1. The first superfluous element will be removed (.. / or //);
	//2. The route searches the new path in a case-insensitive manner.
	//3. If the handler is found correctly, the route is redirected to the correct handler and returns either 301 or 307. //Foo may be redirected to /Foo)
	router.RedirectFixedPath = true

	{
		home.GET("/", HomeControoler.Index)
		home.GET("/Hi", HomeControoler.Hi)
	}

	serverConfig := ConfigService.GetServerConfig()
	router.Run(serverConfig.HTTP_PORT) // Listen and start the service on 127.0.0.1:8888
}

Copy the code

The project address

Github.com/panle666/Go…