gin中multipart/urlencoded绑定

package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

type LoginForm struct {
	// form:"user" 表示前端提交form表单时User对应的key的名称为:user
	// binding: "required" required表示前端必须传入该键才可以
	User string `form:"user" binding:"required"`
	Password string `form:"password" binding:"required"`
}

func main() {
	router := gin.Default()
	router.POST("/login", func(c *gin.Context) {
		var form LoginForm
		// 你可以使用显示绑定声明绑定 multipart form
		//if err := c.ShouldBindWith(&form, binding.Form); err == nil {
		// 先校验用户传参是否符合LoginForm的校验约束
		// 或者简单的使用ShouldBind方法自动绑定,在这种情况下将自动选择合适的绑定
		if err := c.ShouldBind(&form); err == nil {
			// 在校验传入的用户名密码是否正确
			if form.User == "user" && form.Password == "password" {
				c.JSON(http.StatusOK, gin.H{"status": "you are logged int"})
			} else {
				c.JSON(http.StatusUnauthorized, gin.H{"status": "Unauthorized"})
			}
		} else {
			fmt.Println(err)
			c.JSON(http.StatusBadRequest, gin.H{"key": "key error"})
		}
	})
	router.Run()
}

  

posted @ 2021-10-20 13:46  专职  阅读(140)  评论(0编辑  收藏  举报