github.com/gogf/gf/v2@v2.7.4/net/ghttp/ghttp_z_unit_feature_request_param_test.go (about)

     1  package ghttp_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"strconv"
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/gogf/gf/v2/frame/g"
    11  	"github.com/gogf/gf/v2/net/ghttp"
    12  	"github.com/gogf/gf/v2/test/gtest"
    13  	"github.com/gogf/gf/v2/util/guid"
    14  )
    15  
    16  type UserReq struct {
    17  	g.Meta `path:"/user" tags:"User" method:"post" summary:"user api" title:"api title"`
    18  	Id     int    `v:"required" d:"1"`
    19  	Name   string `v:"required" in:"cookie"`
    20  	Age    string `v:"required" in:"header"`
    21  	// header,query,cookie,form
    22  }
    23  
    24  type UserRes struct {
    25  	g.Meta `mime:"text/html" example:"string"`
    26  }
    27  
    28  var (
    29  	User = cUser{}
    30  )
    31  
    32  type cUser struct{}
    33  
    34  func (c *cUser) User(ctx context.Context, req *UserReq) (res *UserRes, err error) {
    35  	g.RequestFromCtx(ctx).Response.WriteJson(req)
    36  	return
    37  }
    38  
    39  func Test_Params_Tag(t *testing.T) {
    40  	s := g.Server(guid.S())
    41  	s.Group("/", func(group *ghttp.RouterGroup) {
    42  		group.Middleware(ghttp.MiddlewareHandlerResponse)
    43  		group.Bind(User)
    44  	})
    45  	s.SetDumpRouterMap(false)
    46  	s.Start()
    47  	defer s.Shutdown()
    48  
    49  	time.Sleep(100 * time.Millisecond)
    50  
    51  	gtest.C(t, func(t *gtest.T) {
    52  		prefix := fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())
    53  		client := g.Client()
    54  		client.SetPrefix(prefix)
    55  		client.SetCookie("name", "john")
    56  		client.SetHeader("age", "18")
    57  
    58  		t.Assert(client.PostContent(ctx, "/user"), `{"Id":1,"Name":"john","Age":"18"}`)
    59  		t.Assert(client.PostContent(ctx, "/user", "name=&age=&id="), `{"Id":1,"Name":"john","Age":"18"}`)
    60  	})
    61  }
    62  
    63  func Benchmark_ParamTag(b *testing.B) {
    64  	b.StopTimer()
    65  
    66  	s := g.Server(guid.S())
    67  	s.Group("/", func(group *ghttp.RouterGroup) {
    68  		group.Middleware(ghttp.MiddlewareHandlerResponse)
    69  		group.Bind(User)
    70  	})
    71  	s.SetDumpRouterMap(false)
    72  	s.SetAccessLogEnabled(false)
    73  	s.SetErrorLogEnabled(false)
    74  	s.Start()
    75  	defer s.Shutdown()
    76  	prefix := fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())
    77  	client := g.Client()
    78  	client.SetPrefix(prefix)
    79  	client.SetCookie("name", "john")
    80  	client.SetHeader("age", "18")
    81  
    82  	b.StartTimer()
    83  	for i := 1; i < b.N; i++ {
    84  		client.PostContent(ctx, "/user", "id="+strconv.Itoa(i))
    85  	}
    86  }