Introduction
API
API(Application Programming Interface),即应用程序接口。API不能单纯地理解为提供数据的接口,而是一个很广的意义。
- 利用函数或者是面向对象的方式提供一些编程的工具。
- 数据API:浏览器需要数据进行渲染,而数据来源于服务器的数据库,此时需要服务器的一个接口程序到数据库获取数据,然后通过这个接口将数据返回给浏览器。
Gin
Gin是一个用Go语言编写的Web框架。它具有类似Martini的API,但由于使用了httprouter,其性能提高了最多40倍。
Gin 的主要特点包括:
- 零分配路由器。
- 高速。
- 中间件支持。
- 无崩溃。
- JSON验证。
- 路由分组。
- 错误管理。
- 内置渲染。
- 可扩展性。
安装
go get github.com/gin-gonic/gin
初始化
gin常用的初始化实例有两种方式:gin.Default()和gin.New():
gin.Default()在gin.New()的基础上,使用gin的日志和错误捕获的中间件。gin.New()只会单独的生成一个HTTP引擎。
package main
import "github.com/gin-gonic/gin"
func main() {
// 初始化gin实例 r代表路由
r := gin.Default()
// r := gin.New()
// 启动
r.Run()
}
基本请求
初始化的实例r有GET、POST等请求封装:
GET
可使用GetQuery或DefaultQuery获取查询参数:
// info?name=tom
r.GET("/info", func(ctx *gin.Context) {
// name, ok := ctx.GetQuery("name")
name := ctx.DefaultQuery("name", "none")
ctx.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "ok",
"data": map[string]any{
"id": 1,
"name": "JASON",
"age": 20,
},
})
})
POST
type UserInfo struct {
Id int32 `json:"id"`
Name string `json:"name"`
Age uint8 `json:"age"`
}
// application/json
r.POST("/info1", func(ctx *gin.Context) {
var info UserInfo
if err := ctx.ShouldBindJSON(&info); err != nil {
panic(err.Error())
}
ctx.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "ok",
"data": map[string]any{
"id": info.Id,
"name": info.Name,
"age": info.Age,
},
})
})
// application/x-www-urlencoded
r.POST("/info2", func(ctx *gin.Context) {
id := ctx.PostForm("id")
name := ctx.DefaultPostForm("name", "wxm1")
age := ctx.DefaultPostForm("age", "none")
ctx.JSON(http.StatusOK, gin.H{
"code": 0,
"msg": "ok",
"data": map[string]any{
"id": id,
"name": name,
"age": age,
},
})
})