"github.com/gin-gonic/gin"
// 使用 gin.BasicAuth() 中介軟體的分組
// gin.Accounts 是 map[string]string 的簡寫
authorized := router.Group("/admin", gin.BasicAuth(gin.Accounts{
// 存取 "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})
c.JSON(http.StatusOK, gin.H{"user": user, "secret": "沒有秘密 :("})
// 在 0.0.0.0:8080 上監聽並提供服務