This is the 22nd day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021
1. Required Environment and recommended software
1.1 Prerequisites
- mysql
- redis
- golang
1.2 Recommended Software
- goland
- navicat
- runapi
2. Initialize the project
- Create a project
- Creating a folder
- The project structure
API ├ mall / ├ ─ ─ ─ ─ the cache ├ ─ ─ the conf ├ ─ ─ middleware ├ ─ ─ model ├ ─ ─ PKG │ ├ ─ ─ e │ ├ ─ ─ util ├ ─ ─ routes ├ ─ ─ serializer └ ─ ─ serviceCopy the code
- API: used to define interface functions - cache: used to store redis cache - conf: used to store configuration files - Middleware: application middleware - model: Application database model - PKG/E: Encapsulation error code - PKG /util: tool function - routes: route logic processing - serializer: function for serializing data to JSON - service: implementation of the interface functionCopy the code
- Go Mod manages package dependencies
- In the source
3. Initialize the configuration file
Create it in confconfig.ini
andconf.go
3.1 the config. Ini
Configure mysql first
#debug development mode,release production mode
[service]
AppMode = debug
HttpPort = :3000
[mysql]
Db = mysql
DbHost = 127.0.0.1
DbPort = 3306
DbUser = root
DbPassWord = root
DbName = mail_db
Copy the code
3.2 the conf. Go
- The configuration file
var (
AppMode string
HttpPort string
Db string
DbHost string
DbPort string
DbUser string
DbPassWord string
DbName string
)
Copy the code
- Reading configuration Files
func Init(a) {
// Read environment variables locally
file, err := ini.Load("./conf/config.ini")
iferr ! =nil {
fmt.Println(Configuration file reading error, please check file path:, err)
}
LoadServer(file)
LoadMysqlData(file)
//MySQL
path := strings.Join([]string{DbUser, ":", DbPassWord, "@tcp(", DbHost, ":", DbPort, "/", DbName, "? charset=utf8&parseTime=true"}, "")
model.Database(path)
}
Copy the code
- Load the configuration
func LoadServer(file *ini.File) {
AppMode = file.Section("service").Key("AppMode").String()
HttpPort = file.Section("service").Key("HttpPort").String()
}
func LoadMysqlData(file *ini.File) {
Db = file.Section("mysql").Key("Db").String()
DbHost = file.Section("mysql").Key("DbHost").String()
DbPort = file.Section("mysql").Key("DbPort").String()
DbUser = file.Section("mysql").Key("DbUser").String()
DbPassWord = file.Section("mysql").Key("DbPassWord").String()
DbName = file.Section("mysql").Key("DbName").String()
}
Copy the code
3.3 the main function
The initial configuration is done in the main function
There are some configurations that are not written in. Redis, seven niuyun configuration of what.
We’ll fill it in later when we need it.