zoukankan      html  css  js  c++  java
  • Form绑定

    其实本质是将c中的request中的body数据解析到form中。

    1. 方法一

    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"net/http"
    	"fmt"
    )
    
    type Login struct {
    	User     string `form:"username" json:"user" uri:"user" xml:"user"  binding:"required"`
    	Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
    }
    
    func main() {
    	router := gin.Default()
    	// Form 绑定普通表单的例子
    	// Example for binding a HTML form (user=hanru&password=hanru123)
    	router.POST("/loginForm", func(c *gin.Context) {
    		var form Login
    		//方法一:对于FORM数据直接使用Bind函数, 默认使用使用form格式解析,if c.Bind(&form) == nil
    		// 根据请求头中 content-type 自动推断.
    		if err := c.Bind(&form); err != nil {
    			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
    			return
    		}
    
    		if form.User != "hanru" || form.Password != "hanru123" {
    			c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
    			return
    		}
    
    		c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
    	})
    
    	router.Run(":8080")
    }

    2. 方法二

    package main
    
    import (
    	"github.com/gin-gonic/gin"
    	"github.com/gin-gonic/gin/binding"
    )
    
    type Login struct {
    	User     string `form:"username" json:"user" uri:"user" xml:"user"  binding:"required"`
    	Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
    }
    
    func main() {
    	router := gin.Default()
    	router.POST("/login", func(c *gin.Context) {
    		var form Login
    		//方法二: 使用BindWith函数,如果你明确知道数据的类型
    		// 你可以显式声明来绑定多媒体表单:
    		// c.BindWith(&form, binding.Form)
    		// 或者使用自动推断:
    		if c.BindWith(&form, binding.Form) == nil {
    			if form.User == "hanru" && form.Password == "hanru123" {
    				c.JSON(200, gin.H{"status": "you are logged in ..... "})
    			} else {
    				c.JSON(401, gin.H{"status": "unauthorized"})
    			}
    		}
    	})
    
    	router.Run(":8080")
    }

  • 相关阅读:
    Python常用转换函数
    Python随机数
    sublime text的pylinter插件设置pylint_rc后提示错误
    使用Pydoc生成文档
    字符编码笔记:ASCII,Unicode和UTF-8
    Windows编程MessageBox函数
    魔方阵算法及C语言实现
    iOS通讯录整合,兼容iOS789写法,附demo
    谈谈iOS app的线上性能监测
    ReactiveCocoa代码实践之-更多思考
  • 原文地址:https://www.cnblogs.com/yzg-14/p/13143851.html
Copyright © 2011-2022 走看看