get/post请求把值绑定到结构体中

get请求把值绑定到结构体中

package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

type UserInfo struct {
	UserName string `json:"username" form:"username"`
	Password string `json:"password" form:"password"`
}

func main() {
	// 创建一个默认的路由引擎
	r := gin.Default()
	// 定义路由
	r.GET("/getUserInfo", func(c *gin.Context) {
		userInfo := &UserInfo{}
		// 这里合并了if外面的判断值
		if err := c.ShouldBindQuery(userInfo); err != nil {
			c.JSON(400, gin.H{
				"message": "参数绑定失败",
			})
			return
		} else {
			// 在控制台:打印绑定好的结构体
			fmt.Printf("#%v", userInfo)
			c.JSON(200, gin.H{
				"message":   "参数绑定成功",
				"user_info": userInfo,
			})
		}
	})
	//  启动服务,端口为8080,当然你也可以更改的哈
	r.Run(":8080")
}

浏览器输入:
http://localhost:8080/getUserInfo?username=1212&password=456

if 中的等价写法

err := c.ShouldBindQuery(userInfo)
if err != nil {
	c.JSON(400, gin.H{
		"message": "参数绑定失败",
	})
	return
}

等价写法

if err := c.ShouldBindQuery(userInfo); err != nil {
  c.JSON(400, gin.H{
    "message": "参数绑定失败",
  })
  return
}

post请求以及解决跨域问题

package main

import (
	"fmt"

	"github.com/gin-gonic/gin"
)

func main() {
	// 创建一个默认的路由引擎
	r := gin.Default()
	// 允许跨域中间件(注意:必须写在路由注册【之前】才对已注册路由生效)
	r.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*") // 允许所有来源(学习阶段够用)
		c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
		c.Header("Access-Control-Allow-Headers", "Content-Type")
		// 浏览器发复杂请求前会先发 OPTIONS 预检,直接放行
		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(204)
			return
		}
		c.Next()
	})
	// 定义路由 post,接收参数 userName password 以及 type,如果type没有默认user
	r.POST("/login", func(c *gin.Context) {
		// 获取post请求传递的参数 userName password 以及 type
		// 通过PostForm方法获取post请求传递的参数 userName password 以及 type
		userName := c.PostForm("userName")
		password := c.PostForm("password")
		// 获取type参数,如果没有传递默认为user
		tpe := c.DefaultPostForm("type", "user")
		fmt.Println(userName, password, tpe)
		c.JSON(200, gin.H{
			"userName": userName,
			"password": password,
			"type":     tpe,
		})
	})

	// 启动服务,端口为8080,当然你也可以更改的哈
	r.Run(":8087")
}
posted @ 2026-10-20 21:52  何人陪我共长生  阅读(7)  评论(0)    收藏  举报