作为一个自然语言处理的 AI 模型,无法直接写 Gin 中间件。但是我可以提供一个示范:
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.Request.Header.Get("Authorization")
if authHeader == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
return
}
authToken := strings.TrimPrefix(authHeader, "Bearer ")
if authToken == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid authorization header"})
return
}
// Here, you can authenticate the user based on the authToken
// For example, you can call an authentication service
// to validate the token and get the user details
// If authentication fails, abort the request with error
// Otherwise, set the user details in the request context
c.Set("user", user)
c.Next()
}
}
这是一个基本的认证中间件,它会从请求的 Authorization 头部获取 JWT token,并将其验证。如果认证通过,将用户信息设置在请求上下文中以便后续处理程序使用。如果认证失败,中止请求并发送错误。
你可以将该中间件添加到你的路由定义中,以在请求执行之前认证用户:
r := gin.Default()
r.Use(AuthMiddleware())
r.GET("/user/:id", func(c *gin.Context) {
user := c.MustGet("user").(*User)
// Now, you can use the authenticated user
c.JSON(http.StatusOK, gin.H{"user": user})
})
r.Run()
此时,所有在 /user/:id
路径下的请求都会先通过 AuthMiddleware 进行认证,之后再由 /user/:id
处理程序处理。
当然,实际中间件可能会更加复杂并考虑更多的情况,比如缓存用户信息以避免反复查找、使用 Redis 等存储认证 token 等。