初始化Go学习项目

This commit is contained in:
liumangmang
2025-12-26 17:56:02 +08:00
commit 7f4527d501
90 changed files with 3436 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
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")
}