package main

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

// 基础认证中间件
func BasicAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		username, password, ok := c.Request.BasicAuth()

		if !ok || username != "admin" || password != "password123" {
			c.JSON(401, gin.H{"error": "Unauthorized"})
			c.Abort()
			return
		}

		// 认证成功，继续
		c.Set("username", username) // 将用户信息存储在 context 中
		c.Next()
	}
}

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

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

	// 需要认证的路由
	r.GET("/protected", BasicAuth(), func(c *gin.Context) {
		username := c.GetString("username")
		c.JSON(200, gin.H{"message": "Hello " + username})
	})

	r.Run(":9999")
}
