深入Gin框架内幕(一):Engine,Route
Context,Bind
Gin框架中使用JWT进行接口验证
1. 获取post请求数据
tag标记为form时,json和form请求字段均小写
tag标记为json时,json请求小写,form请求首字母大写
1. 获取post请求form表单提交的数据
type user struct {
Username string `form:"username"`
Password string `form:"password"`
}
func main() {
r := gin.Default()
r.POST("hello", func(c *gin.Context) {
/* 不定参 获取
c.Request.ParseForm()
for k, v := range c.Request.PostForm {
fmt.Println("--------------")
fmt.Printf("%v\n",k)
fmt.Printf("%v\n",v)
fmt.Println("--------------")
}
*/
var u user
err := c.ShouldBind(&u)
if err!=nil{
c.JSON(http.StatusOK,gin.H{
"error":err.Error(),
})
}else{
fmt.Printf("%v\n",u)
c.JSON(http.StatusOK,gin.H{
"name":u.Username,
"pwd":u.Password,
})
}
})
r.Run()
}
2. 获取post请求json提交的数据
type msg struct {
Name string `json:"name"`
Age int `json:"age"`
}
func main() {
r := gin.Default()
r.POST("hello", func(c *gin.Context) {
var u user
err := c.ShouldBind(&u)
if err!=nil{
c.JSON(http.StatusOK,gin.H{
"error":err.Error(),
})
}else{
fmt.Printf("%v\n",u)
c.JSON(http.StatusOK,gin.H{
"name":u.Username,
"pwd":u.Password,
})
}
})
r.Run()
}
2. 重定向
r.LoadHTMLFiles("index.html")
r.GET("/re", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently,"www.baidu.com")
})
r.GET("/a", func(c *gin.Context) {
c.Request.URL.Path="/index"
r.HandleContext(c)
})
r.GET("/index", func(c *gin.Context) {
//c.JSON(http.StatusOK,gin.H{
// "msg":"index",
//})
c.HTML(http.StatusOK,"index.html",nil)
})
2.中间件
func authMid(doCheck bool) gin.HandlerFunc {
return func(c *gin.Context) {
if doCheck {
//连接数据库等逻辑
} else {
c.Next()
}
}
}
3.gorm使用指针方式实现零值存入数据库
// 使用指针
type User struct {
ID int64
Name *string `gorm:"default:'小王子'"`
Age int64
}
user := User{Name: new(string), Age: 18))}
db.Create(&user) // 此时数据库中该条记录name字段的值就是''
## 4. 中间件
```go
// 定义中间
func MiddleWare() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
fmt.Println("中间件开始执行了")
// 设置变量到Context的key中,可以通过Get()取
c.Set("request", "中间件")
status := c.Writer.Status()
fmt.Println("中间件执行完毕", status)
t2 := time.Since(t)
fmt.Println("time:", t2)
}
}
本文详细介绍了Gin框架中如何获取POST请求的form表单和JSON数据,包括不同tag标记下的处理规则,并探讨了重定向及中间件的使用。此外,还提及了使用Gorm通过指针将零值存入数据库的方法。
533

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



