middleware.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package middleware
  2. import (
  3. "log"
  4. "net/http"
  5. "strconv"
  6. "time"
  7. "github.com/gin-contrib/cors"
  8. "github.com/gin-gonic/gin"
  9. )
  10. func Logger() gin.HandlerFunc {
  11. return func(c *gin.Context) {
  12. start := time.Now()
  13. //继续调用后续的中间件处理函数
  14. c.Next()
  15. log.Printf("[GIN] %s %s %d %s",
  16. c.Request.Method, c.Request.URL.Path, c.Writer.Status(), time.Since(start))
  17. }
  18. }
  19. func CORS() gin.HandlerFunc {
  20. return cors.New(cors.Config{
  21. AllowOrigins: []string{"*"},
  22. AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
  23. AllowHeaders: []string{"Origin", "Content-Type", "Accept"},
  24. AllowCredentials: false,
  25. })
  26. }
  27. // RequireAuth 认证中间件:要求请求头中包含有效的 X-User-Id
  28. func RequireAuth() gin.HandlerFunc {
  29. return func(c *gin.Context) {
  30. userIDStr := c.GetHeader("X-User-Id")
  31. if userIDStr == "" {
  32. c.JSON(http.StatusUnauthorized, gin.H{"error": "未授权访问,请提供 X-User-Id 请求头"})
  33. c.Abort()
  34. return
  35. }
  36. userID, err := strconv.ParseUint(userIDStr, 10, 64)
  37. if err != nil || userID == 0 {
  38. c.JSON(http.StatusUnauthorized, gin.H{"error": "用户ID不合法"})
  39. c.Abort()
  40. return
  41. }
  42. // 将用户ID存储到上下文中,供后续使用
  43. c.Set("user_id", uint(userID))
  44. c.Next()
  45. }
  46. }