example_basic.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package main
  2. import (
  3. "github.com/gin-gonic/gin"
  4. )
  5. var DB = make(map[string]string)
  6. func main() {
  7. r := gin.Default()
  8. // Ping test
  9. r.GET("/ping", func(c *gin.Context) {
  10. c.String(200, "pong")
  11. })
  12. // Get user value
  13. r.GET("/user/:name", func(c *gin.Context) {
  14. user := c.Params.ByName("name")
  15. value, ok := DB[user]
  16. if ok {
  17. c.JSON(200, gin.H{"user": user, "value": value})
  18. } else {
  19. c.JSON(200, gin.H{"user": user, "status": "no value"})
  20. }
  21. })
  22. // Authorized group (uses gin.BasicAuth() middleware)
  23. // Same than:
  24. // authorized := r.Group("/")
  25. // authorized.Use(gin.BasicAuth(gin.Credentials{
  26. // "foo": "bar",
  27. // "manu": "123",
  28. //}))
  29. authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
  30. "foo": "bar", // user:foo password:bar
  31. "manu": "123", // user:manu password:123
  32. }))
  33. authorized.POST("admin", func(c *gin.Context) {
  34. user := c.MustGet(gin.AuthUserKey).(string)
  35. // Parse JSON
  36. var json struct {
  37. Value string `json:"value" binding:"required"`
  38. }
  39. if c.EnsureBody(&json) {
  40. DB[user] = json.Value
  41. c.JSON(200, gin.H{"status": "ok"})
  42. }
  43. })
  44. // Listen and Server in 0.0.0.0:8080
  45. r.Run(":8080")
  46. }