github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_unit_router_handler_extended_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package ghttp_test 8 9 import ( 10 "context" 11 "fmt" 12 "github.com/gogf/gf/errors/gerror" 13 "testing" 14 "time" 15 16 "github.com/gogf/gf/frame/g" 17 "github.com/gogf/gf/net/ghttp" 18 "github.com/gogf/gf/test/gtest" 19 ) 20 21 func Test_Router_Handler_Extended_Handler_Basic(t *testing.T) { 22 p, _ := ports.PopRand() 23 s := g.Server(p) 24 s.BindHandler("/test", func(ctx context.Context) { 25 r := g.RequestFromCtx(ctx) 26 r.Response.Write("test") 27 }) 28 s.SetPort(p) 29 s.SetDumpRouterMap(false) 30 s.Start() 31 defer s.Shutdown() 32 33 time.Sleep(100 * time.Millisecond) 34 gtest.C(t, func(t *gtest.T) { 35 client := g.Client() 36 client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) 37 38 t.Assert(client.GetContent("/test"), "test") 39 }) 40 } 41 42 func Test_Router_Handler_Extended_Handler_WithObject(t *testing.T) { 43 type TestReq struct { 44 Age int 45 Name string 46 } 47 type TestRes struct { 48 Id int 49 Age int 50 Name string 51 } 52 p, _ := ports.PopRand() 53 s := g.Server(p) 54 s.Use(ghttp.MiddlewareHandlerResponse) 55 s.BindHandler("/test", func(ctx context.Context, req *TestReq) (res *TestRes, err error) { 56 return &TestRes{ 57 Id: 1, 58 Age: req.Age, 59 Name: req.Name, 60 }, nil 61 }) 62 s.BindHandler("/test/error", func(ctx context.Context, req *TestReq) (res *TestRes, err error) { 63 return &TestRes{ 64 Id: 1, 65 Age: req.Age, 66 Name: req.Name, 67 }, gerror.New("error") 68 }) 69 s.SetPort(p) 70 s.SetDumpRouterMap(false) 71 s.Start() 72 defer s.Shutdown() 73 74 time.Sleep(100 * time.Millisecond) 75 gtest.C(t, func(t *gtest.T) { 76 client := g.Client() 77 client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) 78 79 t.Assert(client.GetContent("/test?age=18&name=john"), `{"code":0,"message":"","data":{"Id":1,"Age":18,"Name":"john"}}`) 80 t.Assert(client.GetContent("/test/error"), `{"code":50,"message":"error","data":null}`) 81 }) 82 }