码迷,mamicode.com
首页 > 其他好文 > 详细

使用BasicAuth()(验证)中间件

时间:2020-06-20 01:31:26      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:UNC   amp   com   mail   get   var   账号   hello   int   

package main

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

var secrets = gin.H{
	"foo":    gin.H{"email": "foo@bar.com", "phone": "123433"},
	"austin": gin.H{"email": "austin@example.com", "phone": "666"},
	"lena":   gin.H{"email": "lena@guapa.com", "phone": "523443"},
}

func main() {

	r := gin.Default()

	// 路由组
	// Accounts --> type Accounts map[string]string
	authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
		// 账号   密码
		"foo":    "bar",
		"austin": "1234",
		"lena":   "hello2",
		"manu":   "4321",
	}))

	authorized.GET("/secrets", func(c *gin.Context) {
		// 变量.(string) 返回value和bool值,变量是interface{}类型
		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 :("})
		}
	})

	r.Run(":8080")
}

  

使用BasicAuth()(验证)中间件

标签:UNC   amp   com   mail   get   var   账号   hello   int   

原文地址:https://www.cnblogs.com/yzg-14/p/13150028.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!