package main import ( "fmt" "net/http" "github.com/gin-gonic/gin" ) type queryHeader struct { MyHeader string `header:"my_header"` MyDemo string `header:"my_demo"` XChain string `header:"X-Chain"` Key string `header:"x-api-key"` } type queryBody struct { Name string `json:"name"` Age int `json:"age"` Sex int `json:"sex"` } type Req struct { Data []ClassReq `json:"data"` } type ClassReq struct { SeriesName string `json:"seriesName"` SeriesIssuer string `json:"seriesIssuer"` ExternalUrl string `json:"externalUrl"` SeriesDes string `json:"seriesDes"` SeriesId []string `json:"seriesId"` TotalDNA int64 `json:"totalDNA"` AssetContracts string `json:"asset_contracts"` } type queryParameter struct { // Year int `form:"year"` // Month int `form:"month"` Code string `form:"code"` } type queryUri struct { Id int `uri:"id"` Name string `uri:"name"` } func bindUri(context *gin.Context) { var q queryUri err := context.ShouldBindUri(&q) if err != nil { context.JSON(http.StatusBadRequest, gin.H{ "result": err.Error(), }) return } context.JSON(http.StatusOK, gin.H{ "result": "绑定成功", "uri": q, }) } func bindQuery(context *gin.Context) { var q queryParameter err := context.ShouldBindQuery(&q) if err != nil { context.JSON(http.StatusBadRequest, gin.H{ "result": err.Error(), }) return } context.JSON(http.StatusOK, gin.H{ "result": "绑定成功", "query": q, }) } func bindBody(context *gin.Context) { fmt.Println(context.Request.Body) var q Req err := context.ShouldBindJSON(&q) if err != nil { fmt.Println(err.Error()) context.JSON(http.StatusBadRequest, gin.H{ "result": err.Error(), }) return } fmt.Printf("%v\n", q) context.JSON(http.StatusOK, gin.H{ "result": "绑定成功", "body": q, }) } func bindhead(context *gin.Context) { var q queryHeader err := context.ShouldBindHeader(&q) if err != nil { context.JSON(http.StatusBadRequest, gin.H{ "result": err.Error(), }) return } context.JSON(http.StatusUnauthorized, gin.H{ "result": "绑定成功", "header": q, }) } func main() { srv := gin.Default() srv.GET("/binding/header", bindhead) srv.POST("/binding/body", bindBody) srv.GET("/binding/query", bindQuery) srv.GET("/binding/:id/:name", bindUri) // srv.Use(CORSMiddleware()) srv.Run(":9999") } func CORSMiddleware() gin.HandlerFunc { // 配置跨域 return func(c *gin.Context) { // 允许的请求源,这里设置为允许所有来源 c.Writer.Header().Set("Access-Control-Allow-Origin", "*") // 允许的请求方法 c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS") // 允许的请求头 // c.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type,Accept-Language,X-Requested-With,Global") c.Writer.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type,Accept-Language,X-Requested-With,Global,Accept,Accept-Encoding,Accept-Language,Cache-Control,Connection,Host,Origin,Pragma,Referer,User-Agent,X-Chain") // 处理 OPTIONS 请求 if c.Request.Method == http.MethodOptions { // 返回成功状态码 c.AbortWithStatus(http.StatusOK) return } c.Next() } } var html = `