1、代码
package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
type postForm1 struct {
UserId string `json:"userid" form:"userid" binding:"required"`
Page []string `json:"page" form:"page" binding:"required"`
}
func main() {
r := gin.Default()
r.POST("/post", func(c *gin.Context) {
id := c.Query("postid")
page := c.DefaultQuery("page", "0")
name := c.PostForm("name")
message := c.PostForm("message")
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
c.JSON(200, gin.H{
"status": "posted",
"id": id,
"page": page,
"name": name,
"message": message,
})
})
r.POST("/post1", func(c *gin.Context) {
var form postForm1
if c.BindJSON(&form) == nil {
c.JSON(200, gin.H{
"status": 200,
"id": form.UserId,
"page": form.Page,
})
}
fmt.Printf("id: %s ", form.UserId)
})
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.GET("/user/:name/:action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
r.GET("/ping1", func(c *gin.Context) {
jsonData := []byte(`{"msg":"this worked"}`)
var v interface{}
json.Unmarshal(jsonData, &v)
data := v.(map[string]interface{})
c.JSON(http.StatusOK, data)
})
r.Run(":8080")
}
注意Post Bind有两种方式如果是Form直接Bind,否则使用BindJson
错误解决办法
gin listen tcp: address 8000: missing port in address
端口前面加:
其中一个测试示例
|
请发表评论