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")
    }

  • 相关阅读:
    分别用Excel和python进行日期格式转换成时间戳格式
    数据分析之数据质量分析和数据特征分析
    BP neural network optimized by PSO algorithm on Ammunition storage reliability prediction 阅读笔记
    Matlab的BP神经网络工具箱及其在函数逼近中的应用
    js 深拷贝+浅拷贝
    git fork了项目之后修改再push给项目
    微信小程序的开发学习(2)
    Django学习
    小程序的开发学习
    JavaScript-闭包理解
  • 原文地址:https://www.cnblogs.com/yzg-14/p/13143851.html
Copyright © 2011-2022 走看看