欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 产业 > Gin框架操作指南06:POST绑定(下)

Gin框架操作指南06:POST绑定(下)

2024/10/24 1:48:10 来源:https://blog.csdn.net/weixin_54259326/article/details/142965509  浏览:    关键词:Gin框架操作指南06:POST绑定(下)

官方文档地址(中文):https://gin-gonic.com/zh-cn/docs/
注:没用过Gin的读者强烈建议先阅读第一节:Gin操作指南:开山篇。
本节继续演示POST绑定,包括将request-body绑定到不同的结构体中;映射查询字符串或表单参数;上传文件 Query和post-form。

目录

    • 一、将request-body绑定到不同的结构体中
    • 二、映射查询字符串或表单参数
    • 三、上传文件
    • 四、Query和post-form

一、将request-body绑定到不同的结构体中

package mainimport ("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", SomeHandler) // 注册路由router.Run(":8080")                       // 启动服务器
}

注意if分支中的注释,效果如下
在这里插入图片描述
在这里插入图片描述
要想多次绑定,可以使用 c.ShouldBindBodyWith.

func SomeHandler(c *gin.Context) {
objA := formA{}
objB := formB{}
// 读取 c.Request.Body 并将结果存入上下文。
if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
c.String(http.StatusOK, the body should be formA)
// 这时, 复用存储在上下文中的 body。
} else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
c.String(http.StatusOK, the body should be formB JSON)
// 可以接受其他格式
} else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
c.String(http.StatusOK, the body should be formB XML)
} else {

}
}
c.ShouldBindBodyWith 会在绑定之前将 body 存储到上下文中。 这会对性能造成轻微影响,如果调用一次就能完成绑定的话,那就不要用这个方法。
只有某些格式需要此功能,如 JSON, XML, MsgPack, ProtoBuf。 对于其他格式, 如 Query, Form, FormPost, FormMultipart 可以多次调用 c.ShouldBind() 而不会造成任任何性能损失 (详见 #1341)。

二、映射查询字符串或表单参数

package mainimport ("fmt" // 导入格式化I/O库"github.com/gin-gonic/gin" // 导入Gin框架
)func main() {router := gin.Default() // 创建默认的Gin路由// 设置处理POST请求的路由router.POST("/post", func(c *gin.Context) {// c.QueryMap("ids") 用于映射查询字符串中的 "ids" 参数// 例如:POST /post?ids[a]=1234&ids[b]=hello// 这个方法会将查询参数转换为一个map,key为参数名,value为参数值ids := c.QueryMap("ids")// c.PostFormMap("names") 用于映射表单数据中的 "names" 参数// 例如:names[first]=thinkerou&names[second]=tianou// 这个方法会将表单数据转换为一个mapnames := c.PostFormMap("names")// 打印解析后的 ids 和 names 的值// ids: map[b:hello a:1234], names: map[second:tianou first:thinkerou]fmt.Printf("ids: %v; names: %v", ids, names)})router.Run(":8080") // 启动服务器并监听8080端口
}

打开postman,输入http://localhost:8080/post?ids[a]=1234&ids[b]=hello
然后在body中添加key和value,注意names[]作为一个key,效果如图
在这里插入图片描述

三、上传文件

在”上传文件”,目录下建立两个文件夹demo01和demo02,demo01用于单文件上传:

package mainimport ("fmt""log""net/http""github.com/gin-gonic/gin"
)func main() {router := gin.Default()// 为 multipart forms 设置较低的内存限制 (默认是 32 MiB)// 将内存限制设置为 8 MiB,这意味着如果上传的文件超过这个大小,// 将会返回错误,确保服务器不会因为大文件上传而耗尽内存router.MaxMultipartMemory = 8 << 20 // 8 MiB// 定义一个 POST 路由,处理文件上传router.POST("/upload", func(c *gin.Context) {// 从请求中获取文件,"file" 是表单字段的名称file, err := c.FormFile("file")if err != nil {// 处理文件获取错误,返回状态码 400 和错误信息c.String(http.StatusBadRequest, "Error retrieving the file")return}// 打印文件名到服务器日志log.Println(file.Filename)// 设置文件保存的目标路径,文件将保存在当前目录下dst := "./" + file.Filename// 上传文件至指定的完整文件路径if err := c.SaveUploadedFile(file, dst); err != nil {// 如果文件保存失败,返回状态码 500 和错误信息c.String(http.StatusInternalServerError, "Unable to save the file")return}// 返回成功信息,告知用户文件已上传c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))})// 启动服务器,监听 8080 端口router.Run(":8080")
}

打开postman,输入http://loaclhost:8080/upload,在body中填充form-data,key=file,类型为File,然后选择文件,选好后点击send,效果如下
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
多文件上传

package mainimport ("fmt""log""net/http""github.com/gin-gonic/gin"
)func main() {router := gin.Default()// 为 multipart forms 设置较低的内存限制 (默认是 32 MiB)// 将内存限制设置为 8 MiB,这意味着如果上传的文件总大小超过这个限制,// 将返回错误,确保服务器不会因为大文件上传而耗尽内存router.MaxMultipartMemory = 8 << 20 // 8 MiB// 定义一个 POST 路由,用于处理文件上传router.POST("/upload", func(c *gin.Context) {// Multipart form// 从请求中获取 multipart 表单数据form, err := c.MultipartForm()if err != nil {// 如果获取 multipart 表单数据失败,返回状态码 400 和错误信息c.String(http.StatusBadRequest, "Failed to get multipart form")return}// 获取上传的文件,"upload[]" 是表单字段的名称files := form.File["upload[]"]// 遍历每个文件for _, file := range files {// 打印文件名到服务器日志log.Println(file.Filename)// 设置文件保存的目标路径,文件将保存在当前目录下dst := "./" + file.Filename// 上传文件至指定目录if err := c.SaveUploadedFile(file, dst); err != nil {// 如果文件保存失败,返回状态码 500 和错误信息c.String(http.StatusInternalServerError, "Unable to save the file")return}}// 返回成功信息,告知用户上传的文件数量c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))})// 启动服务器,监听 8080 端口router.Run(":8080")
}

在这里插入图片描述

四、Query和post-form

package mainimport ("fmt""github.com/gin-gonic/gin"
)func main() {// 创建一个新的 Gin 路由引擎router := gin.Default()// 定义一个 POST 路由,用于处理 POST 请求router.POST("/post", func(c *gin.Context) {// 从查询字符串中获取 "id" 参数id := c.Query("id")// 从查询字符串中获取 "page" 参数,如果未提供,则返回默认值 "0"page := c.DefaultQuery("page", "0")// 从 POST 请求的表单数据中获取 "name" 参数name := c.PostForm("name")// 从 POST 请求的表单数据中获取 "message" 参数message := c.PostForm("message")// 打印获取到的参数值到标准输出fmt.Printf("id: %s; page: %s; name: %s; message: %s\n", id, page, name, message)})// 启动 HTTP 服务器,监听 8080 端口router.Run(":8080")
}

效果
在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com