preface
I'm a programmer. This is the tutorial (part2) for creating the zero foundation of gin + vue. I will update the front and back source code of this tutorial to my gitee account synchronously: https://gitee.com/coderwusi . github account: https://github.com/coderwusi.
Create a new project root folder, gin base cli, and create a new main.go under the root folder, as follows:
package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // Listen and start the service on 0.0.0.0:8080 }
Use go modules, the package management tool of go, and enter the following contents under cmd to initialize:
go mod init gin-base-cli
Enter the following to update the dependency
go mod tidy
Episode: go modules and go path
Gopath is set by setting the variable name gopath and the variable value folder directory
When the go mod tidy command is used for dependency collation, the newly added package will appear in the path of gopath
matters needing attention
- Using the go mod command will only sort out your project dependencies, but the packages you download will not be lost.
- The dependencies of all items on a machine will be in the gopath directory. The gopath directory may take up more and more space over time, so it's best not to put it in the system disk.
Back to the point
Execute under the project root directory
go run main.go
Access after program compilation
http://localhost:8080/ping
If it is displayed as follows, it indicates that gin is successfully imported
Introduce viper
Create a new config.yaml file in the root directory
mysql: host: "127.0.0.1" port: 3306 suffix: "charset=utf8mb4&parseTime=True&loc=Local" #suffix dbname: "wusidb" username: "root" password: "123456" max_open_conns: 200 max_idle_conns: 50
Create a new folder named setting. Under the setting folder, create init.go:
package setting import ( "fmt" "github.com/spf13/viper" //Third party configuration management artifact ) var Conf = new(TotalConfig) type TotalConfig struct { *MySQLConfig `mapstructure:"mysql"` } type MySQLConfig struct { Host string `mapstructure:"host"` Username string `mapstructure:"username"` Password string `mapstructure:"password"` Dbname string `mapstructure:"dbname"` Suffix string `mapstructure:"suffix"` Port int `mapstructure:"port"` MaxOpenConns int `mapstructure:"max_open_conns"` MaxIdleConns int `mapstructure:"max_idle_conns"` } func init() () { viper.SetConfigFile("config.yaml") //viper.AddConfigPath("./") if err := viper.ReadInConfig(); err != nil { fmt.Printf("viper.ReadInConfig failed, err:%v\n", err) return } if err := viper.Unmarshal(Conf); err != nil { fmt.Printf("viper.Unmarshal failed, err:%v\n", err) } fmt.Println(Conf.MySQLConfig) }
Import setting in main.go:
package main import ( _ "gin-base-cli/setting" //Import setting.init to complete initialization "github.com/gin-gonic/gin" ) func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // Listen and start the service on 0.0.0.0:8080 }
Execute command collation dependency
go mod tidy
Execute the go run main.go launcher
As shown in the figure above, if the file in config.yaml is printed, it indicates that the third-party configuration library viper is successfully imported.
The current directory structure is as follows:
Insert picture description here
Introducing Gorm
Gorm is a very good orm framework, which can greatly speed up the efficiency of writing sql statements
Create a new model folder under the root directory, and create init.go under the model folder:
package model import ( "fmt" "gin-base-cli/setting" "gorm.io/driver/mysql" "gorm.io/gorm" "gorm.io/gorm/schema" ) // DB database link singleton var DB *gorm.DB func MysqlInit(config *setting.MySQLConfig) () { var err error dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?%s", config.Username, config.Password, config.Host, config.Port, config.Dbname, config.Suffix) DB, err = gorm.Open(mysql.New(mysql.Config{ DSN: dsn, // DSN data source name DefaultStringSize: 256, // The default length of a string type field DisableDatetimePrecision: true, // Disable datetime precision, which is not supported in MySQL databases before 5.6 DontSupportRenameIndex: true, // When renaming an index, delete and create a new one. Databases before MySQL 5.7 and MariaDB do not support renaming an index DontSupportRenameColumn: true, // Use 'change' to rename the column. Databases before MySQL 8 and MariaDB do not support renaming the column SkipInitializeWithVersion: false, // Automatically configure according to the current MySQL version }), &gorm.Config{NamingStrategy: schema.NamingStrategy{SingularTable: true}}) if err != nil { fmt.Println("Database connection error:", err) return } if err := DB.AutoMigrate(); err != nil { fmt.Println("Database migration error:", err) return } fmt.Println("success") }
Modify main.go:
package main import ( "gin-base-cli/model" "gin-base-cli/setting" "github.com/gin-gonic/gin" ) func main() { setting.Init() model.MysqlInit(setting.Conf.MySQLConfig) r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // Listen and start the service on 0.0.0.0:8080 }
The go run main.go command starts the program. If the following information is printed, it indicates that gorm is successfully introduced:
Stage summary
So far, the reading of environment variables and the connection to mysql database have come to an end. The current directory structure is as follows:
I am a programmer Wusi. If you like this series of articles, please praise and support it!