Using BasicAuth() middleware

  1. // simulate some private data
  2. var secrets = gin.H{
  3. "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},
  4. "austin": gin.H{"email": "austin@example.com", "phone": "666"},
  5. "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
  6. }
  7. func main() {
  8. r := gin.Default()
  9. // Group using gin.BasicAuth() middleware
  10. // gin.Accounts is a shortcut for map[string]string
  11. authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
  12. "foo": "bar",
  13. "austin": "1234",
  14. "lena": "hello2",
  15. "manu": "4321",
  16. }))
  17. // /admin/secrets endpoint
  18. // hit "localhost:8080/admin/secrets
  19. authorized.GET("/secrets", func(c *gin.Context) {
  20. // get user, it was set by the BasicAuth middleware
  21. user := c.MustGet(gin.AuthUserKey).(string)
  22. if secret, ok := secrets[user]; ok {
  23. c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
  24. } else {
  25. c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
  26. }
  27. })
  28. // Listen and serve on 0.0.0.0:8080
  29. r.Run(":8080")
  30. }