github.com/gogf/gf@v1.16.9/net/ghttp/ghttp_unit_context_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  	"testing"
    12  	"time"
    13  
    14  	"github.com/gogf/gf/frame/g"
    15  	"github.com/gogf/gf/net/ghttp"
    16  	"github.com/gogf/gf/test/gtest"
    17  )
    18  
    19  func Test_Context(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  			r.SetCtxVar("traceid", 123)
    25  			r.Middleware.Next()
    26  		})
    27  		group.GET("/", func(r *ghttp.Request) {
    28  			r.Response.Write(r.GetCtxVar("traceid"))
    29  		})
    30  	})
    31  	s.SetPort(p)
    32  	s.SetDumpRouterMap(false)
    33  	s.Start()
    34  	defer s.Shutdown()
    35  
    36  	time.Sleep(100 * time.Millisecond)
    37  	gtest.C(t, func(t *gtest.T) {
    38  		client := g.Client()
    39  		client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
    40  
    41  		t.Assert(client.GetContent("/"), `123`)
    42  	})
    43  }