Gin 学习笔记03-参数绑定

参数绑定

  • 1、ShouldBindJSON
  • 2、ShouldBindQuery
  • 3、ShouldBindUri
  • 4、ShouldBind

1、ShouldBindJSON

package main

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

type User struct {
	Name   string `json:"name"`
	Gender string `json:"gender"`
	Age    int    `json:"age"`
}

func getUser(c *gin.Context) {
	var userInfo User
	err := c.ShouldBindJSON(&userInfo)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"message": "参数错误"})
		return
	}
	c.JSON(http.StatusOK, userInfo)
}

func main() {
	router := gin.Default()
	router.GET("/user", getUser)
	router.Run(":9090")
}

2、ShouldBindQuery

package main

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

type UserInfo struct {
	Name   string `json:"name" form:"name"`
	Gender string `json:"gender" form:"gender"`
	Age    string `json:"age" form:"age"`
}

func getUserInfo(c *gin.Context) {
	var userInfo UserInfo
	err := c.ShouldBindQuery(&userInfo)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"message": "参数有误"})
		return
	}
	c.JSON(http.StatusOK, userInfo)
}

func main() {
	router := gin.Default()
	router.POST("/user", getUserInfo)
	router.Run("9090")
}

3、ShouldBindUri

package main

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

func bindUri(c *gin.Context) {
	type User struct {
		Name string `json:"name" uri:"name"`
		Age  int    `json:"age" uri:"age"`
	}

	var user User

	c.ShouldBindUri(&user)

	c.JSON(http.StatusOK, user)
}

func main() {
	router := gin.Default()

	router.GET("/uri/:name/:age", bindUri)

	router.Run(":9000")
}


4、ShouldBind

package main

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

type Students struct {
	Name   string `json:"name" form:"name"`
	Gender string `json:"gender" form:"gender"`
	Age    int    `json:"age" form:"age"`
}

func getStudent(c *gin.Context) {
	var userInfo Students
	err := c.ShouldBind(&userInfo)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"message": "参数错误"})
		return
	}
	c.JSON(http.StatusOK, userInfo)
}

func main() {
	router := gin.Default()
	router.GET("/user", getStudent)
	router.Run(":9000")
}

你可能感兴趣的:(gin,学习,笔记)