gin/examples/basic/main.go

66 lines
1.3 KiB
Go
Raw Normal View History

2014-06-18 03:42:34 +04:00
package main
import (
"net/http"
2014-06-18 03:42:34 +04:00
"github.com/gin-gonic/gin"
)
var DB = make(map[string]string)
func setupRouter() *gin.Engine {
// Disable Console Color
// gin.DisableConsoleColor()
2014-06-18 03:42:34 +04:00
r := gin.Default()
// Ping test
r.GET("/ping", func(c *gin.Context) {
c.String(http.StatusOK, "pong")
2014-06-18 03:42:34 +04:00
})
// Get user value
r.GET("/user/:name", func(c *gin.Context) {
user := c.Params.ByName("name")
value, ok := DB[user]
if ok {
c.JSON(http.StatusOK, gin.H{"user": user, "value": value})
2014-06-18 03:42:34 +04:00
} else {
c.JSON(http.StatusOK, gin.H{"user": user, "status": "no value"})
2014-06-18 03:42:34 +04:00
}
})
// Authorized group (uses gin.BasicAuth() middleware)
// Same than:
// authorized := r.Group("/")
// authorized.Use(gin.BasicAuth(gin.Credentials{
// "foo": "bar",
// "manu": "123",
//}))
authorized := r.Group("/", gin.BasicAuth(gin.Accounts{
"foo": "bar", // user:foo password:bar
"manu": "123", // user:manu password:123
2014-06-18 03:42:34 +04:00
}))
authorized.POST("admin", func(c *gin.Context) {
user := c.MustGet(gin.AuthUserKey).(string)
2014-06-18 03:42:34 +04:00
// Parse JSON
var json struct {
Value string `json:"value" binding:"required"`
}
2015-05-22 17:55:16 +03:00
if c.Bind(&json) == nil {
2014-06-18 03:42:34 +04:00
DB[user] = json.Value
c.JSON(http.StatusOK, gin.H{"status": "ok"})
2014-06-18 03:42:34 +04:00
}
})
return r
}
func main() {
r := setupRouter()
2014-06-18 03:42:34 +04:00
// Listen and Server in 0.0.0.0:8080
r.Run(":8080")
2014-06-18 03:42:34 +04:00
}