package main

import (
	"fmt"
	"time"

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

// 日志中间件
func LoggerMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		// 记录请求信息
		startTime := time.Now()
		method := c.Request.Method
		url := c.Request.URL.Path

		// 继续处理
		c.Next()

		// 记录响应信息
		statusCode := c.Writer.Status()
		duration := time.Since(startTime)

		fmt.Printf("[%s] %s %d ( %v)\n", method, url, statusCode, duration)
	}
}

func main() {
	r := gin.New() // 不使用默认中间件

	// 使用自定义日志中间件
	r.Use(LoggerMiddleware())
	r.Use(gin.Recovery())

	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{"message": "Hello"})
	})

	r.GET("/slow", func(c *gin.Context) {
		time.Sleep(100 * time.Millisecond)
		c.JSON(200, gin.H{"message": "Slow endpoint"})
	})

	r.Run(":9999")
}
