一、表单实体绑定
(1) FORM格式绑定
type User struct{
UserName string `form:"username" binding:"required"`
Phone string `form:"phone" binding:"required"`
}
-
处理GET请求:
context:上下文var user Use err := context.ShouldBindQuery(&user) -
处理POST请求
1. var user User context.ShouldBind(&user)
(2)JSON格式绑定
context.BindJSON(&user)
二、多数据格式返回请求结果
context.Writer.Write([]byte("string"))
-
返回 JSON 格式
context.JSON(200, gin.H{ key: value }) -
HTML页面
engine.LoadHTMLGlob("./html/*") //加载静态文件在
engine.GET()之前context.HTML(200, "index.html", obj:nil)HTML属于静态文件
3.1 数据返回到HTML页面
–模板语言
{{.fullPath}}obj: gin.H{ "fullPath": fullPath, }3.2 加载静态文件
<img src="...">设置静态资源目录:engine.Static(访问路径:"/img", 目录路径: "./img")
三、请求路由组的使用
engine := gin.Default()
userGroup := engine.Group("/user") //分级
userGroup.Get("/register", function(context *gin.context))
3.1 补充:Delete操作
engine.Delete("/:id", func(context *gin.Context){
userID := context.Param(key:"id")
})
四、中间件
func Middleware() gin.HandlerFunc{
return func(context *gin.Context){
path := context.FullPath()
method := context.Request.Method
fmt.Println("请求路径:", path)
fmt.Println("请求方法: ", method)
}
}
func main(){
engine := gin.Default()
engine.Use(Middleware())
engine.GET("/PATH", Middleware(), func(context, *gin.Context){
...
})
}
context.Next()
//context.Next()将中间件执行的函数一分为二,遇到context.Next(),程序不再往下执行,系统寻找下一个gin.Context类型。
本文介绍了Gin框架中如何使用FORM和JSON格式进行数据绑定,包括表单实体结构定义、GET和POST请求处理,以及响应数据的不同返回方式,如字符串、JSON和HTML。同时探讨了请求路由组的应用和中间件的使用技巧。
3627

被折叠的 条评论
为什么被折叠?



