package main

import (
	"fmt"
	"time"

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

// 日志中间件
func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		c.Next()
		duration := time.Since(start)
		fmt.Printf("[%s] %s %d (%v)\n",
			c.Request.Method, c.Request.URL.Path, c.Writer.Status(), duration)
	}
}

// 认证中间件
func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token != "Bearer secret" {
			c.JSON(401, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}
		c.Next()
	}
}

// Recovery 中间件
func Recovery() gin.HandlerFunc {
	return func(c *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				c.JSON(500, gin.H{"error": "Internal Server Error"})
				c.Abort()
			}
		}()
		c.Next()
	}
}

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

	// 全局中间件
	r.Use(Logger())
	r.Use(Recovery())

	// 公开路由
	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Public"})
	})

	// 需要认证的路由组
	auth := r.Group("/api")
	auth.Use(Auth())
	{
		auth.GET("/users", func(c *gin.Context) {
			c.JSON(200, gin.H{"users": []string{"Alice", "Bob"}})
		})

		auth.POST("/users", func(c *gin.Context) {
			c.JSON(201, gin.H{"message": "User created"})
		})
	}

	r.Run(":9999")
}
