github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_unit_request_ctx_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/frame/g" 13 "github.com/gogf/gf/net/ghttp" 14 "github.com/gogf/gf/test/gtest" 15 "testing" 16 "time" 17 ) 18 19 func Test_Request_SetCtx(t *testing.T) { 20 p, _ := ports.PopRand() 21 s := g.Server(p) 22 s.Group("/", func(group *ghttp.RouterGroup) { 23 group.Middleware(func(r *ghttp.Request) { 24 ctx := context.WithValue(r.Context(), "test", 1) 25 r.SetCtx(ctx) 26 r.Middleware.Next() 27 }) 28 group.ALL("/", func(r *ghttp.Request) { 29 r.Response.Write(r.Context().Value("test")) 30 }) 31 }) 32 s.SetPort(p) 33 s.SetDumpRouterMap(false) 34 s.Start() 35 defer s.Shutdown() 36 37 time.Sleep(100 * time.Millisecond) 38 gtest.C(t, func(t *gtest.T) { 39 c := g.Client() 40 c.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) 41 42 t.Assert(c.GetContent("/"), "1") 43 }) 44 }