github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/ginx/adapt/adapt_test.go (about) 1 package adapt_test 2 3 import ( 4 "fmt" 5 "net/http" 6 "testing" 7 8 "github.com/bingoohuang/gg/pkg/ginx/adapt" 9 "github.com/bingoohuang/gg/pkg/ginx/gintest" 10 "github.com/gin-gonic/gin" 11 "github.com/stretchr/testify/assert" 12 ) 13 14 func TestNoAdapt(t *testing.T) { 15 r := gin.New() 16 17 // This handler will match /user/john but will not match /user/ or /user 18 r.GET("/user/:name", func(c *gin.Context) { 19 c.Set("Xyz", "First") 20 }, func(c *gin.Context) { 21 name := c.Param("name") 22 c.Header("Xyz", c.GetString("Xyz")+" Second") 23 c.String(http.StatusOK, "Hello %s", name) 24 }) 25 26 // r.Run(":8080") 27 28 rr := gintest.Get("/user/bingoohuang", r) 29 assert.Equal(t, "Hello bingoohuang", rr.Body()) 30 assert.Equal(t, "First Second", rr.Header().Get("Xyz")) 31 } 32 33 func TestAdapt(t *testing.T) { 34 r := adapt.Adapt(gin.New()) 35 r.RegisterAdapter(func(f func(string) string) gin.HandlerFunc { 36 return func(c *gin.Context) { 37 c.String(http.StatusOK, f(StringArg(c))) 38 } 39 }) 40 41 // This handler will match /user/john but will not match /user/ or /user 42 r.GET("/user/:name", func(name string) string { 43 return fmt.Sprintf("Hello %s", name) 44 }) 45 46 // This handler will match /user/john but will not match /user/ or /user 47 r.GET("/direct/:name", func(c *gin.Context) { 48 c.String(http.StatusOK, "Hello Direct %s", c.Param("name")) 49 }) 50 51 // r.Run(":8080") 52 53 rr := gintest.Get("/user/bingoohuang", r) 54 assert.Equal(t, "Hello bingoohuang", rr.Body()) 55 56 rr = gintest.Get("/direct/bingoohuang", r) 57 assert.Equal(t, "Hello Direct bingoohuang", rr.Body()) 58 } 59 60 func TestGroup(t *testing.T) { 61 r := adapt.Adapt(gin.New()) 62 63 r.RegisterAdapter(func(f func(string) string) gin.HandlerFunc { 64 return func(c *gin.Context) { 65 c.String(http.StatusOK, f(StringArg(c))) 66 } 67 }) 68 69 v1 := r.Group("/v1") 70 v1.POST("/login", func(user string) string { return "Hello1 " + user }) 71 72 v2 := r.Group("/v2") 73 v2.POST("/login", func(user string) string { return "Hello2 " + user }) 74 75 rr := gintest.Post("/v1/login", r, gintest.Query("user", "bingoohuang")) 76 assert.Equal(t, "Hello1 bingoohuang", rr.Body()) 77 78 rr = gintest.Post("/v2/login", r, gintest.Query("user", "dingoohuang")) 79 assert.Equal(t, "Hello2 dingoohuang", rr.Body()) 80 } 81 82 func StringArg(c *gin.Context) string { 83 if len(c.Params) == 1 { 84 return c.Params[0].Value 85 } 86 87 if q := c.Request.URL.Query(); len(q) == 1 { 88 for _, v := range q { 89 return v[0] 90 } 91 } 92 93 return "" 94 }