github.com/wangyougui/gf/v2@v2.6.5/net/ghttp/ghttp_z_unit_feature_server_util_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/wangyougui/gf. 6 7 package ghttp_test 8 9 import ( 10 "fmt" 11 "net/http" 12 "testing" 13 "time" 14 15 "github.com/wangyougui/gf/v2/frame/g" 16 "github.com/wangyougui/gf/v2/net/ghttp" 17 "github.com/wangyougui/gf/v2/test/gtest" 18 "github.com/wangyougui/gf/v2/util/guid" 19 ) 20 21 type testWrapStdHTTPStruct struct { 22 T *gtest.T 23 text string 24 } 25 26 func (t *testWrapStdHTTPStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) { 27 t.T.Assert(req.Method, "POST") 28 t.T.Assert(req.URL.Path, "/api/wraph") 29 w.WriteHeader(http.StatusInternalServerError) 30 fmt.Fprint(w, t.text) 31 } 32 33 func Test_Server_Wrap_Handler(t *testing.T) { 34 gtest.C(t, func(t *gtest.T) { 35 s := g.Server(guid.S()) 36 str1 := "hello" 37 str2 := "hello again" 38 s.Group("/api", func(group *ghttp.RouterGroup) { 39 group.GET("/wrapf", ghttp.WrapF(func(w http.ResponseWriter, req *http.Request) { 40 t.Assert(req.Method, "GET") 41 t.Assert(req.URL.Path, "/api/wrapf") 42 w.WriteHeader(http.StatusBadRequest) 43 fmt.Fprint(w, str1) 44 })) 45 46 group.POST("/wraph", ghttp.WrapH(&testWrapStdHTTPStruct{t, str2})) 47 }) 48 49 s.SetDumpRouterMap(false) 50 s.Start() 51 defer s.Shutdown() 52 53 time.Sleep(100 * time.Millisecond) 54 client := g.Client() 55 client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d/api", s.GetListenedPort())) 56 57 response, err := client.Get(ctx, "/wrapf") 58 t.AssertNil(err) 59 defer response.Close() 60 t.Assert(response.StatusCode, http.StatusBadRequest) 61 t.Assert(response.ReadAllString(), str1) 62 63 response2, err := client.Post(ctx, "/wraph") 64 t.AssertNil(err) 65 defer response2.Close() 66 t.Assert(response2.StatusCode, http.StatusInternalServerError) 67 t.Assert(response2.ReadAllString(), str2) 68 }) 69 }