package main
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
engine := gin.Default()
engine.Use(middlewareGlobal)
engine.Any("/demo", demo)
engine.Any("/demo/:name", middleware1, middleware2, middleware3, hello)
engine.Run(":8081")
}
func demo(context *gin.Context) {
context.String(http.StatusOK, "demo")
}
func hello(context *gin.Context) {
name := context.Param("name")
test := context.GetString("test")
log.Printf("test: %s!", test)
log.Printf("Hello %s!", name)
context.String(http.StatusOK, "Hello %s!", name)
}
func middlewareGlobal(context *gin.Context) {
log.Printf("Global middleware")
context.Next()
}
func middleware1(context *gin.Context) {
buf := make([]byte, 1024)
num, _ := context.Request.Body.Read(buf)
log.Printf("middleware1: %s\n", string(buf[:num]))
context.Next()
}
func middleware2(context *gin.Context) {
log.Printf("middleware2: start")
context.Next()
log.Printf("middleware2: end")
}
func middleware3(context *gin.Context) {
context.Set("test", "1234567890")
context.Next()
}