1. 實體綁定
以一個用戶注冊功能來進行表單實體綁定操作
用戶注冊需要提交表單數據,假設注冊時表單數據包含三項:
- username
- phone
- password
我們創建一個UserRegister結構體用於接收表單數據,通過tag標簽的方式設置每個字段對應的form表單中的屬性名,通過binding字段設置該屬性是否為必須
type UserRegister struct { Username string `form:"username" binding:"required"` Phone string `form:"phone" binding:"required"` Password string `form:"password" binding:"required"` }
1.1 ShouldBindQuery解析GET參數
使用ShouldBindQuery可以實現Get方法的數據請求綁定,具體實現如下:
// get // http://localhost:8080/register?name=james&phone=8888&password=123456 engine.GET("/register",func(ctx *gin.Context) { var user UserRegister err:=ctx.ShouldBindQuery(&user) if err!=nil{ log.Fatal(err.Error()) } ctx.Writer.Write([]byte("hello "+user.Username)) })
1.2 ShouldBind解析POST參數
// post // http://localhost:8080/register engine.POST("/register", func(ctx *gin.Context) { var user UserRegister err := ctx.ShouldBind(&user) if err != nil { log.Fatal(err.Error()) } ctx.Writer.Write([]byte("hello " + user.Username)) })
1.3 BindJSON解析POST請求json格式數據
// post // http://localhost:8080/addstu engine.POST("/addstu", func(ctx *gin.Context) { var stu Student err := ctx.BindJSON(&stu) if err != nil { log.Fatal(err.Error()) } ctx.Writer.Write([]byte("hello " + stu.Name)) })
2. 多數據格式返回請求結果
在gin框架中,支持多種返回請求數據格式
2.1 []byte
通過context.Writer.Write方法寫入byte切片數據
ctx.Writer.Write([]byte("hello " + stu.Name))
如上面這句代碼所示,使用context.Writer.Write向客戶端寫入返回數據
Writer是gin框架中封裝的一個ResponseWriter接口類型,在這個interface中包含了met/http標准庫下的ResponseWriter
2.2 string
通過context.Writer.WriteString方法寫入string類型數據
ctx.Writer.WriteString("hello " + stu.Name)
2.3 json
gin為了方便開發者更方便地使用,支持將返回數據組裝成json格式進行返回
gin框架中的context包含的json方法可以將結構體數據轉成json格式的結構化數據,然后返回給客戶端
2.3.1 map -> json
// get json // http://localhost:8080/hellojson engine.GET("/hellojson", func(ctx *gin.Context) { ctx.JSON(200, map[string]interface{}{ "code": 1, "message": "ok", "data": ctx.FullPath(), }) })
2.3.2 struct -> json
// get json // http://localhost:8080/hellojson engine.GET("/hellojson", func(ctx *gin.Context) { resp := Response{ Code: 1, Message: "ok", Data: ctx.FullPath(), } ctx.JSON(200, &resp) })
2.4 html模版和靜態資源
當我們需要返回一個html頁面或者一些靜態資源(圖片等)時,gin也提供了一些方法
首先我們需要創建一個html模版,前后端交互的模版語句很簡單,就是使用{{}}來表示這是一個模版變量
{{.title}} {{.fullPath}}
然后我們在后端注冊路由,完成html模版的渲染
需要注意的是,gin必須要先設置html目錄為可加載狀態,才可以向客戶端返回html
// get html // http://localhost:8080/hellohtml // 設置html目錄 engine.LoadHTMLGlob("./html/*") // 如果html里包含圖片 engine.Static("/img", "./img")
engine.GET("/hellohtml", func(ctx *gin.Context) { ctx.HTML(http.StatusOK, "index.html", gin.H{ "title": "hello gin", "fullPath": ctx.FullPath(), }) })
在項目開發時,一些靜態的資源文件如html、js、css等都可以通過靜態資源文件設置的方式來進行設置