Golang实现API


package main

import (
	"database/sql"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"log"
)

var db *sql.DB
var err error

func main() {

	DatabaseInit()

	gin.SetMode(gin.ReleaseMode)

	r := gin.Default()

	r.GET("/", IndexAction)

	r.GET("/ping", PingAction)

	r.GET("/user/:name", UserAction)

	r.GET("/agent", AgentAction)

	r.Run()
}

func DatabaseInit() {

	db, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/wordpress")
	if err != nil {
		log.Fatalln(err)
	}
	defer db.Close()

	db.SetMaxIdleConns(20)
	db.SetMaxOpenConns(20)

	err = db.Ping()
	if err != nil {
		log.Fatalln(err)
	}

}

func IndexAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "index"})
}

func PingAction(c *gin.Context) {
	c.JSON(200, gin.H{"message": "pong"})
}

func UserAction(c *gin.Context) {
	c.String(200, "Hello %s", c.Param("name"))
}

func AgentAction(c *gin.Context) {
	c.String(200, c.GetHeader("user-agent"))
}