gin框架中的数据解析与绑定
阅读原文时间:2023年07月08日阅读:2

Json数据解析与绑定

客户端传参,后端接收并解析到结构体

func Login(context *gin.Context) {
    // 声明接收的变量
    var login LoginJson
    // 将request的body中的数据,自动按照json格式解析到结构体
    // 等价于:context.ShouldBindWith(&login, binding.JSON)
    if err := context.ShouldBindJSON(&login); err != nil {
        context.JSON(http.StatusBadRequest, err.Error())
        return
    }
    // 判断用户名密码是否正确
    if login.User != "root" || login.Password != "admin" {
        fmt.Println("用户名或密码错误")
        context.JSON(http.StatusBadRequest, gin.H{"status": 304})
        return
    }
    context.String(http.StatusOK, "OK")
}

表单数据解析和绑定

func Login(context *gin.Context) {
    // 声明接收的变量
    var login LoginJson
    // Bind默认解析并绑定Form格式
    // 根据请求头中的Content-Type自动推断
    // binding.Form是form-data类型, binding.FormPost是x-www-form-urlencoded类型
    if err := context.ShouldBindWith(&login, binding.FormPost); err != nil {
        context.JSON(http.StatusBadRequest, err.Error())
        return
    }
    // 判断用户名密码是否正确
    if login.User != "root" || login.Password != "admin" {
        fmt.Println("用户名或密码错误")
        context.JSON(http.StatusBadRequest, gin.H{"status": 304})
        return
    }
    context.String(http.StatusOK, "OK")
}

URI数据解析和绑定

func Login(context *gin.Context) {
    // 声明接收的变量
    var login LoginJson

    if err := context.ShouldBindUri(&login); err != nil {
        context.JSON(http.StatusBadRequest, err.Error())
        return
    }
    // 判断用户名密码是否正确
    if login.User != "root" || login.Password != "admin" {
        fmt.Println("用户名或密码错误")
        context.JSON(http.StatusBadRequest, gin.H{"status": 304})
        return
    }
    context.String(http.StatusOK, "OK")
}

注意:Uri请求应该写成这样: router.POST("/login/:username/:password", Login)

http://127.0.0.1:8080/login/root/admin

结构体中也可以定义相关的字段标签:

// 定义接收数据的结构体
type LoginJson struct {
    User string `form:"username" json:"username" uri:"username" binding:"required"`
    Password string `form:"password" json:"password" uri:"password" binding:"required"`
}

上传单个或多个文件

// 上传单个文件
func UploadFile(context *gin.Context) {
    file, _ := context.FormFile("file")
    // 注意此目录是相对于项目的目录,而不是当前文件的目录
    context.SaveUploadedFile(file, "./app/files/" + file.Filename)
    context.JSON(200, "upload file ok")
}

// 上传多个文件
func UploadFiles(context *gin.Context) {
    form, _ := context.MultipartForm()
    files := form.File["file"]
    for _, file := range files {
        context.SaveUploadedFile(file, "./app/files/" + file.Filename)
    }
    context.JSON(200, "upload files ok")
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器