一、初始化项目
mkdir go-app
cd go-app
go mod init app
二、设置第三方依赖包
go get github.com/go-sql-driver/mysql@v1.5.0
go get github.com/gin-gonic/gin@v1.6.3
go get github.com/gomodule/redigo/redis@v1.8.3
三、开始编码
package main
import (
"database/sql"
"log"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
func main() {
databaseInit()
defer db.Close()
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.GET("/", IndexAction)
r.GET("/user/:name", UserAction)
r.Run()
}
func databaseInit() {
var err error
db, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/wordpress")
if err != nil {
log.Fatalln(err)
}
db.SetMaxIdleConns(500)
db.SetMaxOpenConns(500)
err = db.Ping()
if err != nil {
log.Fatalln(err)
}
}
func IndexAction(c *gin.Context) {
c.JSON(200, gin.H{"message": "index"})
}
func UserAction(c *gin.Context) {
var ID int
err := db.QueryRow("SELECT ID FROM wp_users WHERE user_login = ?", c.Param("name")).Scan(&ID)
if err == nil {
c.String(200, "Hello %d", ID)
} else {
c.String(200, "Hello nobody")
}
}
四、生成本地依赖
go mod vendor
五、运行
go run -mod=vendor main.go