学习目标
- POST方式请求JSON格式,解析并绑定JSON对象
curl -X POST -H "Content-type:application/json" \
-d '{ "name":"zhangsan","age":20,"sex":"male"}' \
http://localhost:8080/api/v1/addstudent
- GET方式解析Query,解析并绑定JSON对象
http://localhost:8080/api/v1/list?name=zhangsan&age=20&sex=female
- GET方式请求,解析URI中的参数
http://localhost:8080/api/v1/zhangsan/1234
课程案例
BindJSON
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
type Person struct {
Name string `form:"name"`
Sex string `form:"sex"`
Age int `form:"age"`
}
func hello(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "hello world"})
}
func jsonHandler(c *gin.Context) {
// 声明接收解析json变量
var json Person
// 解析request 中json格式数据
if err := c.BindJSON(&json); err != nil {
// 解析错误返回结果
c.JSON(http.StatusBadRequest, gin.H{"status": err.Error()})
return
}
// 解析通过业务处理
//.....
// 返回处理状态
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"name": json.Name,
"sex": json.Sex,
"age": json.Age,
})
}
func main() {
// 1.创建路由
// 默认使用了2个中间件Logger(), Recovery()
r := gin.Default()
// 注册hello函数
r.GET("/hello", hello)
// request json格式解析
r.POST("/api/v1/addstudent", jsonHandler)
r.Run(":8080")
}
/***
运行方式1:命令行方式:
curl -X POST -H "Content-type:application/json" \
-d '{ "name":"zhangsan","age":20,"sex":"male"}' \
http://localhost:8080/api/v1/addstudent
运行方式2:postman/Apifox 方式运行
*/
ShouldBindQuery
package main
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
type Person struct {
Name string `form:"name"`
Sex string `form:"sex"`
Age int `form:"age"`
}
func hello(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "hello world"})
}
func bindQueryHandler(c *gin.Context) {
// 声明接收解析json变量
var json Person
// 解析request 中json格式数据
if err := c.ShouldBindQuery(&json); err != nil {
// 解析错误返回结果
c.JSON(http.StatusBadRequest, gin.H{"status": err.Error()})
return
}
// 解析通过业务处理
fmt.Println("name = ", json.Name)
fmt.Println("age = ", json.Age)
//.....
// 返回处理状态
c.JSON(http.StatusOK, gin.H{
"status": "ok",
"name": json.Name,
"sex": json.Sex,
"age": json.Age,
})
}
func main() {
// 1.创建路由
// 默认使用了2个中间件Logger(), Recovery()
r := gin.Default()
// 注册hello函数
r.GET("/hello", hello)
// request json格式解析
// http://localhost:8080/api/v1/list?name=zhangsan&age=20&sex=female
r.GET("/api/v1/list", bindQueryHandler)
r.Run(":8080")
}
ShouldBindUri
package main
import (
"github.com/gin-gonic/gin"
)
// 定义接收参数结构体
type Student struct {
// 通过uri 标记记录输入的参数
ID string `uri:"id"`
Name string `uri:"name"`
}
func main() {
r := gin.Default()
r.GET("/api/v1/:name/:id", func(c *gin.Context) {
// 声明接收请求参数变量
var student Student
// 将路由参数绑定到结构体中
if err := c.ShouldBindUri(&student); err != nil {
c.JSON(400, gin.H{"msg": err})
return
}
// 正常返回
c.JSON(200, gin.H{"name": student.Name, "ID": student.ID})
})
r.Run(":8080")
}
/**
1、启动服务
2、通过curl -v 命令测试,其中-v选项可打印完成的响应信息
curl -v http://localhost:8080/api/v1/zhangsan/1234
*/