路由分组
使用 路由分组 可以将一组有关联的路由放到一起,方便管理和查看,具体实现代码如下:
r1 := r.Group("/home") //分组的1级路径
{ //这里的大括号可有可无,加上大括号是为了方便清晰的阅读代码
r11 := r.Group("user") //分组的2级路径
{
r11.POST("/login", controllers.Login) //请求路径: /home/user/login
r11.POST("/logout", controllers.Logout) //请求路径: /home/user/logout
r11.GET("/info:user_id", controllers.UserInfo) //请求路径: /home/user/info?user_id=1
}
}
请求参数绑定
如何将client提交的ison数据与Server对应的对象(实体/结构体)进行关联?Gin框架提供了Bind,可以根据请求Body数据,将数据赋值到指定的结构体变量中。Gin框架中的的bind方法,主要是将结构体与请求参数进行绑定,请求参数json对应的key就是结构体对应的字段。如下代码:
// 接口客户端请求的参数
type ClientRequest struct {
UserName string `json:"user_name" binding:"required"`
Password string `json:"password" binding:"required"`
Remark string `json:"remark"`
}
// 返回客户端的数据
type ClientResponse struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
// 登录操作
func Login(c *gin.Context) {
var requestData ClientRequest
var response ClientResponse
err := c.Bind(&requestData) //执行绑定
//fmt.Println("绑定的数据:", requestData)
if err != nil {
fmt.Println("错误信息:", err)
response.Code = http.StatusBadRequest
response.Msg = "请求参数错误"
c.JSON(http.StatusBadRequest, response)
return
}
if requestData.UserName == "zhangsan" && requestData.Password == "123456" {
response.Code = http.StatusOK
response.Msg = "登录成功"
response.Data = "OK"
c.JSON(http.StatusOK, response)
return
}
c.JSON(http.StatusBadRequest, ClientResponse{
Code: http.StatusBadRequest,
Msg: "登录失败",
Data: nil,
})
return
}
请求三方接口登录
如果是请求三方接口(比如微信登录),需要将对方接口需要的参数封装后发送HTTP请求,然后接收对方的返回。代码如下:
// 请求三方服务登录
func ThirdLogin(c *gin.Context) {
//调用第三方接口的请求数据
type ThirdAPIRequest struct {
LoginUserName string `json:"login_user_name"`
LoginPassword string `json:"login_password"`
}
//调用第三方接口的返回结果
type ThirdAPIResponse struct {
Code int `json:"res_code"`
Msg string `json:"res_message"`
Data string `json:"res_data"`
}
var requestData ClientRequest
err := c.Bind(&requestData) //执行绑定
if err != nil {
fmt.Println("错误信息:", err)
c.JSON(http.StatusBadRequest, ClientResponse{
Code: http.StatusBadRequest,
Msg: "参数错误",
})
return
}
//请求第三方API接口数据
url := "http://localhost/t.php"
requestThirdData := ThirdAPIRequest{
LoginUserName: requestData.UserName,
LoginPassword: requestData.Password,
}
data, err := requestAPI(url, requestThirdData, "application/json")
var responseThirdData ThirdAPIResponse
json.Unmarshal(data, &responseThirdData)
fmt.Println("responseThirdData", responseThirdData)
c.JSON(http.StatusOK, ClientResponse{
Code: responseThirdData.Code,
Msg: responseThirdData.Msg,
Data: responseThirdData.Data,
})
return
}
// 发送POST请求
// url: 请求地址
// data: POST请求提交的数据
// contentType: 请求体格式,如:application/json
// content: 请求放回的内容
func requestAPI(url string, data interface{}, contentType string) ([]byte, error) {
//创建调用API接口的client
client := &http.Client{Timeout: 5 * time.Second}
jsonStr, _ := json.Marshal(data)
fmt.Println("请求三方接口信息:", url, bytes.NewBuffer(jsonStr))
resp, err := client.Post(url, contentType, bytes.NewBuffer(jsonStr))
if err != nil {
fmt.Println("调用API接口出现了错误:", err)
return nil, err
}
res, err := ioutil.ReadAll(resp.Body)
fmt.Println("三方接口返回信息:", bytes.NewBuffer(res), err)
return res, err
}
第三方服务使用PHP代码模拟,如下:
<?php
$request = file_get_contents("php://input");
$request = json_decode($request, true);
if (empty($request['login_user_name']) || empty($request['login_password'])) {
echo json_encode(["res_code" => -1, "res_message" => "参数不全"]);
exit;
}
if ($request['login_user_name'] == "zhangsan" && $request['login_password'] == "123456") {
echo json_encode(["res_code" => 200, "res_message" => "登录成功"]);
exit;
} else {
echo json_encode(["res_code" => 500, "res_message" => "登录失败"]);
exit;
}
数据校验
基础校验
如果需要复杂的校验,可以使用一些专业的库来完成,其中 go-playground/validator
就是一款优秀的Go语言校验库,基于标记为结构体和单个字段实现值验证。
添加依赖:go get github.com/go-playground/validator
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/go-playground/validator"
"github.com/satori/go.uuid"
"net/http"
"unicode/utf8"
)
var validate *validator.Validate
func init() {
validate = validator.New()
validate.RegisterValidation("checkName", checkNameFunc)
}
func checkNameFunc(f validator.FieldLevel) bool {
count := utf8.RuneCountInString(f.Field().String())
if count >= 2 && count <= 12 {
return true
}
return false
}
func UpdateUser(c *gin.Context) {
type UserData struct {
Id string `validate:"uuid" json:"id"` //UUID 类型
Name string `validate:"checkName" json:"name"` //自定义校验,长度2到12
Age uint8 `validate:"min=0,max=120" json:"age"` //0<=Age<=120
}
var user UserData
err := c.Bind(&user)
if err != nil {
c.JSON(http.StatusBadRequest, "请求参数错误!")
return
}
//自定义校验
err = validate.Struct(user)
if err != nil {
//输出错误的校验值
for _, e := range err.(validator.ValidationErrors) {
fmt.Println("错误的字段:", e.Field())
fmt.Println("错误的值:", e.Value())
fmt.Println("错误的tag:", e.Tag())
}
c.JSON(http.StatusBadRequest, "数据校验失败")
return
}
c.JSON(http.StatusOK, "成功")
return
}
// 生成uuid
func CreateUuid(c *gin.Context) {
fmt.Println("uuid", uuid.NewV4())
}
输入错误的参数:
输入正确的参数:
生成uuid的方法:go get github.com/satori/go.uuid,然后 uuid.NewV4()
嵌套结构的校验
使用 dive关键字表示进入到嵌套结构体进行判断。
func CheckUserV2(c *gin.Context) {
//更多校验规则: https://github.com/go-playground/validator
type ValAddress struct {
Province string `validate:"required" json:"province"` //非空
City string `validate:"required" json:"city"` //非空
Phone string `validate:"numeric,len=11" json:"phone"` //数字类型,长度为11
}
type ValUser struct {
Name string `validate:"required" json:"name"` //非空
Age uint8 `validate:"gte=0,lte=130" json:"age"` // 0<=Age<=130
Email string `validate:"required,email" json:"email"` //非空,email格式
Address []ValAddress `validate:"dive" json:"address"` //dive关键字表示进入到嵌套结构体进行判断
}
//参数绑定
var user ValUser
err := c.Bind(&user)
if err != nil {
c.JSON(http.StatusBadRequest, "参数错误,绑定失败!")
return
}
//执行参数的校验
err = validate.Struct(user)
if err != nil {
//断言为:validator.ValidationErrors,类型为:[]FieldError
for _, e := range err.(validator.ValidationErrors) {
fmt.Println("错误的字段:", e.Field())
fmt.Println("错误的值:", e.Value())
fmt.Println("错误的tag:", e.Tag())
}
c.JSON(http.StatusBadRequest, "数据校验失败!")
return
}
c.JSON(http.StatusOK, "数据校验成功!")
return
}
源代码:https://gitee.com/rxbook/gin-demo