github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_unit_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/gogf/gf. 6 7 package ghttp_test 8 9 import ( 10 "fmt" 11 "net/http" 12 "testing" 13 "time" 14 15 "github.com/gogf/gf/frame/g" 16 "github.com/gogf/gf/net/ghttp" 17 "github.com/gogf/gf/test/gtest" 18 ) 19 20 type testWrapStdHTTPStruct struct { 21 T *gtest.T 22 text string 23 } 24 25 func (t *testWrapStdHTTPStruct) ServeHTTP(w http.ResponseWriter, req *http.Request) { 26 t.T.Assert(req.Method, "POST") 27 t.T.Assert(req.URL.Path, "/api/wraph") 28 w.WriteHeader(http.StatusInternalServerError) 29 fmt.Fprint(w, t.text) 30 } 31 func Test_Server_Wrap_Handler(t *testing.T) { 32 gtest.C(t, func(t *gtest.T) { 33 p, _ := ports.PopRand() 34 s := g.Server(p) 35 str1 := "hello" 36 str2 := "hello again" 37 s.Group("/api", func(group *ghttp.RouterGroup) { 38 group.GET("/wrapf", ghttp.WrapF(func(w http.ResponseWriter, req *http.Request) { 39 t.Assert(req.Method, "GET") 40 t.Assert(req.URL.Path, "/api/wrapf") 41 w.WriteHeader(http.StatusBadRequest) 42 fmt.Fprint(w, str1) 43 })) 44 45 group.POST("/wraph", ghttp.WrapH(&testWrapStdHTTPStruct{t, str2})) 46 }) 47 48 s.SetPort(p) 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", p)) 56 57 response, er1 := client.Get("/wrapf") 58 defer response.Close() 59 t.Assert(er1, nil) 60 t.Assert(response.StatusCode, http.StatusBadRequest) 61 t.Assert(response.ReadAllString(), str1) 62 63 response2, er2 := client.Post("/wraph") 64 defer response2.Close() 65 t.Assert(er2, nil) 66 t.Assert(response2.StatusCode, http.StatusInternalServerError) 67 t.Assert(response2.ReadAllString(), str2) 68 }) 69 }