github.com/gogf/gf/v2@v2.7.4/net/gclient/gclient_z_unit_request_obj_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 gclient_test
     8  
     9  import (
    10  	"fmt"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/gogf/gf/v2/frame/g"
    15  	"github.com/gogf/gf/v2/net/ghttp"
    16  	"github.com/gogf/gf/v2/test/gtest"
    17  	"github.com/gogf/gf/v2/util/guid"
    18  )
    19  
    20  func Test_Client_DoRequestObj(t *testing.T) {
    21  	type UserCreateReq struct {
    22  		g.Meta `path:"/user" method:"post"`
    23  		Id     int
    24  		Name   string
    25  	}
    26  	type UserCreateRes struct {
    27  		Id int
    28  	}
    29  	type UserQueryReq struct {
    30  		g.Meta `path:"/user/{id}" method:"get"`
    31  		Id     int
    32  	}
    33  	type UserQueryRes struct {
    34  		Id   int
    35  		Name string
    36  	}
    37  	s := g.Server(guid.S())
    38  	s.Group("/user", func(group *ghttp.RouterGroup) {
    39  		group.GET("/{id}", func(r *ghttp.Request) {
    40  			r.Response.WriteJson(g.Map{"id": r.Get("id").Int(), "name": "john"})
    41  		})
    42  		group.POST("/", func(r *ghttp.Request) {
    43  			r.Response.WriteJson(g.Map{"id": r.Get("Id")})
    44  		})
    45  	})
    46  	s.SetDumpRouterMap(false)
    47  	s.Start()
    48  	defer s.Shutdown()
    49  
    50  	time.Sleep(100 * time.Millisecond)
    51  	gtest.C(t, func(t *gtest.T) {
    52  		url := fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())
    53  		client := g.Client().SetPrefix(url).ContentJson()
    54  		var (
    55  			createRes *UserCreateRes
    56  			createReq = UserCreateReq{
    57  				Id:   1,
    58  				Name: "john",
    59  			}
    60  		)
    61  		err := client.DoRequestObj(ctx, createReq, &createRes)
    62  		t.AssertNil(err)
    63  		t.Assert(createRes.Id, 1)
    64  	})
    65  	gtest.C(t, func(t *gtest.T) {
    66  		url := fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())
    67  		client := g.Client().SetPrefix(url).ContentJson()
    68  		var (
    69  			queryRes *UserQueryRes
    70  			queryReq = UserQueryReq{
    71  				Id: 1,
    72  			}
    73  		)
    74  		err := client.DoRequestObj(ctx, queryReq, &queryRes)
    75  		t.AssertNil(err)
    76  		t.Assert(queryRes.Id, 1)
    77  		t.Assert(queryRes.Name, "john")
    78  	})
    79  }