go gin 全局中间件,以及设置值

package main

import (
	"fmt"
	"net/http"

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

type User struct {
	UserName string
	Email    string
}

func middleware(c *gin.Context) {
	fmt.Println("进入中间件")
	c.Set("user", User{UserName: "ellis", Email: "haha"})
	c.Next()
	// c.Abort()
	fmt.Println("从中间件离开")
}

func _method(c *gin.Context) {
	user, _ := c.Get("user")
	//断言,类型转换
	u, _ := user.(User)
	c.JSON(http.StatusOK, gin.H{"msg": u})
}

func main() {
	router := gin.Default()
	router.Use(middleware)
	router.GET("/", _method)
	router.Run(":8080")
}

你可能感兴趣的:(GO,golang,gin,中间件)