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

  • 相关阅读:
    元组类型内置方法
    列表类型内置方法
    字符串类型内置方法
    转:【英语学习材料】
    转:【15年学不会英语的原因】
    转:【Java动态编程(Javassist研究)】
    转:【进制转换-概念】
    c语言学习笔记
    virtualbox虚拟机桥接方式网络设置
    navicat连接mysql8报错,错误提示为1251,原因及解决步骤
  • 原文地址:https://www.cnblogs.com/yzg-14/p/13143851.html
Copyright © 2011-2022 走看看