gin使用BasicAuth中间件

package main

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

// 模拟一些私人数据
var secrets = gin.H{
"foo": gin.H{"email": "1341935532@qq.com", "phone": 15313067271},
"austin": gin.H{"email": "myn_net@163.com", "phone": 15188945949},
"lena": gin.H{"email": "8810612@qq.com", "phone": 8810612},
}

func main() {
router := gin.Default()
// 注册BasicAuth中间件
authorized := router.Group("/admin", gin.BasicAuth(gin.Accounts{
"foo": "123465",
"austin": "1234",
"lena": "hello",
"menu": "123",
}))
// admin/secrets 端点,走认证代理
authorized.GET("/login", func(context *gin.Context) {
// 获取用户,它是由 BasicAuth 中间件设置的
userName := context.MustGet(gin.AuthUserKey).(string)
if info, ok := secrets[userName]; ok {
context.JSON(http.StatusOK, gin.H{"userName": userName, "info": info})
} else {
context.JSON(http.StatusOK, gin.H{"userName": userName, "info": "暂无其个人信息"})
}
})

// json端点,不走认证代理
router.GET("/json", func(context *gin.Context) {
context.JSON(200, "OK")
})
router.Run()
}

  

posted @ 2021-10-22 11:34  专职  阅读(482)  评论(0编辑  收藏  举报