Go语言常用知识(二)—— Gin
Gin
func main(){
// 返回json
//创建一个默认的路由引擎
r := gin.Default()
// 1. 使用map
r.GET("/map_json", func(c *gin.Context){
c.JSON(http.StatusOK, gin.H{
"message" : "Hello Golang!",
})
})
// 2. 结构体
type msg struct{
Name string `json:"name"` //反射时用到,可以让解析出的json文件Name字段变成name
Age int
}
r.GET("/struct_json", func(c *gin.Context) {
data := msg{
Name:"老王",
Age: 18,
}
c.JSON(http.StatusOK,data)
})
r.Run(":9090")
}
善用 ShouldBind函数
- 可以获取 querystring
- form表单
- json
type UserInfo struct {
Name string `form:"name"`
Age int `form:"age"`
}
r.POST("/form", func(c *gin.Context) {
var u UserInfo
err := c.ShouldBind(&u)
if err !=nil{
c.JSON(http.StatusBadRequest,gin.H{
"error":err.Error(),
})
}else {
fmt.Printf("%#v\n",u)
c.JSON(http.StatusOK,gin.H{
"name":u.Name,
"age":u.Age,
})
}
路由组
r.Group("/xxx") //xxx是公用的前缀
Gin中间件
定义中间件
Gin的中间件必须是一个gin.HandlerFunc
类型。
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func indexHandler(c *gin.Context){
fmt.Println("index ")
//使用 Set Get 从中间件中 存取数据到 indexHandler中
name, ok := c.Get("name")
if !ok{
name = "nil"
}
c.JSON(http.StatusOK,gin.H{
"name":name,
})
}
//定义一个中间件m1 计时
func m1(c *gin.Context){
fmt.Println("m1 in...")
start := time.Now()
//使用 Set Get 从中间件中 存取数据到 indexHandler中
c.Set("name","zhangsan")
c.Next() //调用后续的处理函数,即后面的 indexHandler
//c.Abort() //阻止调用后续的处理函数
cost := time.Since(start)
fmt.Printf("cost : %v\n", cost)
fmt.Println("m1 out...")
}
func main() {
r := gin.Default() //Default 默认使用 logger 和 recovery 中间件
/**
* Get函数定义如下,最后可以跟多个 handlers类型的参数
*func (group *RouterGroup) GET(relativePath string, handlers ...HandlerFunc) IRoutes {
* return group.handle(http.MethodGet, relativePath, handlers)
*}
*/
//还可以全局注册中间件函数 m1
r.Use(m1)
r.GET("/index", indexHandler)
r.Run(":9090")
}