Gin 的 中间件和异步协程的使用

中间件分为全局中间件,单个路由中间件和群组中间件

package main
import (
    "gopkg.in/gin-gonic/gin.v1"
    "net/http"
    "fmt"
)


func main(){
    // only set in Production
    // gin.SetMode(gin.ReleaseMode)  

    router := gin.Default()

    // 单个路由中间件
    router.GET("/before", MiddleWare(), func(c *gin.Context) {
        request := c.MustGet("request").(string)
        c.JSON(http.StatusOK, gin.H{
            "middile_request": request,
        })
    })

    // 群组中间件
    authorized := router.Group("/")
    // 使用中间件
    authorized.Use(MiddleWare())
    {
        authorized.POST("/login", func(c *gin.Context) {
            c.String(http.StatusOK, "This is User Post MOdel~")
        })
    }


    // 全局中间件
    router.Use(MiddleWare())
    {
        router.GET("/middleware", func(c *gin.Context) {
            request := c.MustGet("request").(string)
            req, _ := c.Get("request")
            c.JSON(http.StatusOK, gin.H{
                "middile_request": request,
                "request": req,
            })
        })
    }
    router.Run(":8005")
}

func MiddleWare() gin.HandlerFunc {
    return func(c *gin.Context) {
        fmt.Println("before middleware")
        c.Set("request", "这是中间件设置的request")
        c.Next()
        fmt.Println("before middleware")
    }
}



使用中间件做用户登陆验证

cookie 设置可以参考 go的cookie 设置

package main
import (
    "gopkg.in/gin-gonic/gin.v1"
    "net/http"
    "fmt"
)


func main(){
    // only set in Production
    // gin.SetMode(gin.ReleaseMode)  

    router := gin.Default()
    router.GET("/auth/signin", func(c *gin.Context) {
        //设置一个10S过期的Cookie 
        cookie := &http.Cookie{
            Name:     "session_id",
            Value:    "seted",
            Path:     "/",
            HttpOnly: true,
            MaxAge : 10,

        }
        http.SetCookie(c.Writer, cookie)
        c.String(http.StatusOK, "Login successful")
    })

    router.GET("/home", AuthMiddleWare(), func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{"data": "LoginWithCoookie successful"})
    })

    router.Run(":8005")
}

func AuthMiddleWare() gin.HandlerFunc {
    return func(c *gin.Context) {
        if cookie, err := c.Request.Cookie("session_id"); err == nil {
            value := cookie.Value
            fmt.Println(value)
            // 验证是否已经设置cookie 
            if value == "seted" {
                c.Next()
                return
            }
        }
        c.JSON(http.StatusUnauthorized, gin.H{
            "error": "Unauthorized",
        })
        c.Abort()
        return
    }
}

异步协程

package main
import (
    "gopkg.in/gin-gonic/gin.v1"
    "time"
    "log"
)


func main(){
    // only set in Production
    // gin.SetMode(gin.ReleaseMode)  

    router := gin.Default()
    router.GET("/sync", func(c *gin.Context) {
        time.Sleep(5 * time.Second)
        //先Sleep 5S ,Print 后  返回http响应
        log.Println("Done! in path" + c.Request.URL.Path)
    })

    router.GET("/async", func(c *gin.Context) {
        //先返回http响应

        // 异步 执行程序 Sleep 5S  后  Print 
        cCp := c.Copy()
        go func() {
            time.Sleep(5 * time.Second)
            log.Println("Done! in path" + cCp.Request.URL.Path)
        }()
    })
    router.Run(":8005")
}

这里写图片描述

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页