官方文档地址(中文):https://gin-gonic.com/zh-cn/docs/
注:本教程采用工作区机制,所以一个项目下载了Gin框架,其余项目就无需重复下载,想了解的读者可阅读第一节:Gin操作指南:开山篇。
本节继续演示POST绑定,包括将request-body绑定到不同的结构体中;映射查询字符串或表单参数;上传文件 Query和post-form。
一、将request-body绑定到不同的结构体中
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
// 定义表单结构体 formA,包含一个必需字段 Foo
type formA struct {
Foo string `json:"foo" xml:"foo" binding:"required"` // 绑定 JSON 和 XML 的字段 foo
}
// 定义表单结构体 formB,包含一个必需字段 Bar
type formB struct {
Bar string `json:"bar" xml:"bar" binding:"required"` // 绑定 JSON 和 XML 的字段 bar
}
// 处理请求的函数
func SomeHandler(c *gin.Context) {
objA := formA{
} // 创建 formA 的实例
objB := formB{
} // 创建 formB 的实例
// c.ShouldBind 使用了 c.Request.Body,不可重用。
if errA := c.ShouldBind(&objA); errA == nil {
// 如果绑定成功,返回表单A的成功信息
c.String(http.StatusOK, `the body should be formA`)
} else if errB := c.ShouldBind(&objB); errB == nil {
// 因为现在 c.Request.Body 是 EOF,所以这里会报错。
c.String(http.StatusOK, `the body should be formB`)
} else {
// 处理绑定错误
c.String(http.StatusBadRequest, `Invalid input`)
}
}
func main() {
router := gin.Default()
router.POST("/some-handler"