1、Gin安装及基础操作

安装:go get -u github.com/gin-gonic/gin

 

初始化:go mod init project

 

使用示例

package main

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

func main() {
    r := gin.Default()  // 比 gin.New 多了 logger 和 recovery (crash-fee)中间件
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}

 

不同的请求方式

func res(c *gin.Context) {
    c.JSON(200, gin.H{
        "message": "pong",
    })
}

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

    r.GET("/ping", res)
    r.POST("/ping",res)
    r.PUT("/ping",res)
    r.DELETE("/ping",res)
    r.PATCH("/ping",res)
    r.HEAD("/ping",res)
    r.OPTIONS("/ping",res)

    r.Run(":7777") // 默认8080
}

 

路由分组

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

    // 路由分组
    group1 := r.Group("/goods")
    group1.GET("ping",res) // 能通过 /goods/ping 访问

    // 路由分组(正常书写模式)
    group2 := r.Group("list")
    {
        group2.HEAD("item",res)
        group2.POST("otherItem",res)
    }
    
    r.Run()
}

 

uri 地址变量获取

    // 动态路由
    r.GET("/book/:id", func(c *gin.Context) { // 变量可以在后面、中间、前面
        id := c.Param("id") // 获取url上的变量
        c.JSON(http.StatusOK, gin.H{
            "key" : id,
        })
    })

    r.GET("/shoes/:item/:ott", func(c *gin.Context) { // 可以有两个变量
        c.JSON(http.StatusOK, gin.H{
            "item" : c.Param("item"),
            "ott" : c.Param("ott"),
        })
    })

    r.GET("/url/*pp", func(c *gin.Context) { // 获取 /url 后面所有的内容
        c.JSON(http.StatusOK, gin.H{
            "item111" : c.Param("pp"),
        })
    })

 

约束 uri 地址变量

    type Person struct {
        Name string    `uri:"name" binding:"required"`
        Age int    `uri:"age" binding:"required"`
    }

    r.GET("judge/:name/:age", func(c *gin.Context) {
        name := c.Param("name")
        age := c.Param("age")

        // 处理错误的传值
        var person Person
        if err := c.ShouldBindUri(&person); err != nil {
            c.JSON(http.StatusNotFound,gin.H{
                "status" : "404",
            })
            return
        }

        c.JSON(http.StatusOK,gin.H{
            "name" : name,
            "age" : age,
        })
    })

 

获取 请求参数

    // 从 get 获取参数
    r.GET("/welcome", func(c *gin.Context) {

        // 带默认值方式
        dd := c.DefaultQuery("dd","i am dd")

        // 不带默认值方式
        cc := c.Query("cc")

        c.JSON(http.StatusOK, gin.H{
            "dd" : dd,
            "cc" : cc,
        })
    })

    // 从 post 获取参数
    r.POST("/welcome-post", func(c *gin.Context) {

        // 带默认值方式
        dd := c.DefaultPostForm("dd","i am dd")

        // 不带默认值方式
        cc := c.PostForm("cc")

        c.JSON(http.StatusOK, gin.H{
            "dd" : dd,
            "cc" : cc,
        })
    })

 

表单验证

package main

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

// 内置表单验证用的包:https://github.com/go-playground/validator

// LoginForm 定义表单字段的规则
type LoginForm struct {
    User string `json:"user" binding:"required,min=3,max=10"`
    Password string `json:"password" binding:"required"`
}

type SignTest struct {
    User string `json:"user" binding:"required,min=3,max=10"`
    Password string `json:"password" binding:"required"`
    RePassword string `json:"re-password" binding:"required,eqfield=Password"` // eqfielf 表明该字段数据和 xxx 数据一样
}

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

    // 登录验证
    r.POST("/testForm", func(c *gin.Context) {

        var loginForm LoginForm

        // 验证不通过就
        if err := c.ShouldBind(&loginForm); err != nil {
            fmt.Println(err.Error())
            c.JSON(http.StatusBadRequest,gin.H{
                "error" : err.Error(),
            })
            return
        }

        // 通过就
        c.JSON(http.StatusOK,gin.H{
            "message" : "success login",
        })
    })

    // 注册验证
    r.POST("/signup", func(c *gin.Context) {

        var signT SignTest

        // 验证不通过就
        if err := c.ShouldBind(&signT); err != nil {
            fmt.Println(err.Error())
            c.JSON(http.StatusBadRequest,gin.H{
                "error" : err.Error(),
            })
            return
        }

        // 通过就
        c.JSON(http.StatusOK,gin.H{
            "message" : "success register",
        })
    })

    r.Run()
}

 

posted @ 2022-02-24 19:03  JaydenQiu  阅读(278)  评论(0)    收藏  举报