Improved BasicAuth() example

This commit is contained in:
Manu Mtz-Almeida 2014-07-04 04:47:34 +02:00
parent 9efd207a04
commit 493008ea3c

View File

@ -320,37 +320,36 @@ func main() {
#### Using BasicAuth() middleware #### Using BasicAuth() middleware
```go ```go
func main() { // similate some private data
r := gin.Default() var secrets = gin.H{
// note than: type gin.H map[string]interface{}
secrets := gin.H{
"foo": gin.H{"email": "foo@bar.com", "phone": "123433"}, "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},
"austin": gin.H{"email": "austin@example.com", "phone": "666"}, "austin": gin.H{"email": "austin@example.com", "phone": "666"},
"lena": gin.H{"email": "lena@guapa.com", "phone": "523443"} "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
} }
func main() {
r := gin.Default()
// Group using gin.BasicAuth() middleware
// gin.Accounts is a shortcut for map[string]string
authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{ authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
"foo": "bar", "foo": "bar",
"austin": "1234", "austin": "1234",
"lena": "hello2", "lena": "hello2",
"manu": "4321" "manu": "4321",
} }))
// /admin/secrets endpoint
// hit "localhost:8080/admin/secrets
authorized.GET("/secrets", func(c *gin.Context) { authorized.GET("/secrets", func(c *gin.Context) {
// get user, it was setted by the BasicAuth middleware // get user, it was setted by the BasicAuth middleware
user := c.GET(gin.AuthUserKey).(string) user := c.Get(gin.AuthUserKey).(string)
if secret, ok := secrets[user]; ok { if secret, ok := secrets[user]; ok {
c.JSON(200, gin.H{ c.JSON(200, gin.H{"user": user, "secret": secret})
"user": user,
"secret": secret
}
} else { } else {
c.JSON(200, gin.H{ c.JSON(200, gin.H{"user": user, "secret": "NO SECRET :("})
"user": user,
"secret": "NO SECRET :("
} }
} })
}
// hit "localhost:8080/admin/secrets
// Listen and server on 0.0.0.0:8080 // Listen and server on 0.0.0.0:8080
r.Run(":8080") r.Run(":8080")