使用 BasicAuth 中间件
// 模拟一些私人数据var secrets = gin.H{}
func main() { router := gin.Default()
// 路由组使用 gin.BasicAuth() 中间件 // gin.Accounts 是 map[string]string 的一种快捷方式 authorized := router.Group("/admin", gin.BasicAuth(gin.Accounts{ "foo": "bar", "austin": "1234", "lena": "hello2", "manu": "4321", }))
// /admin/secrets 端点 // 触发 "localhost:8080/admin/secrets authorized.GET("/secrets", func(c *gin.Context) { // 获取用户,它是由 BasicAuth 中间件设置的 user := c.MustGet(gin.AuthUserKey).(string) if secret, ok := secrets[user]; ok { c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret}) } else { c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("}) } })
// 监听并在 0.0.0.0:8080 上启动服务 router.Run(":8080")}