From 3e33d66ab4ca7e26e28d5f0bcecbabafa08e06e0 Mon Sep 17 00:00:00 2001 From: John Guo Date: Sat, 30 Jan 2021 23:05:02 +0800 Subject: [PATCH] fix issue https://github.com/gogf/gf/issues/1148 --- net/ghttp/ghttp_unit_client_test.go | 20 ++++++++++++++++++++ net/ghttp/internal/client/client.go | 8 ++++---- net/ghttp/internal/client/client_request.go | 4 ---- 3 files changed, 24 insertions(+), 8 deletions(-) diff --git a/net/ghttp/ghttp_unit_client_test.go b/net/ghttp/ghttp_unit_client_test.go index 5f8c73112..0845b8be7 100644 --- a/net/ghttp/ghttp_unit_client_test.go +++ b/net/ghttp/ghttp_unit_client_test.go @@ -421,3 +421,23 @@ func Test_Client_Middleware(t *testing.T) { t.Assert(resp, nil) }) } + +func Test_Client_Agent(t *testing.T) { + p, _ := ports.PopRand() + s := g.Server(p) + s.BindHandler("/", func(r *ghttp.Request) { + r.Response.Write(r.UserAgent()) + }) + s.SetPort(p) + s.SetDumpRouterMap(false) + s.Start() + defer s.Shutdown() + + time.Sleep(100 * time.Millisecond) + + gtest.C(t, func(t *gtest.T) { + c := g.Client().SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p)) + c.SetAgent("test") + t.Assert(c.GetContent("/"), "test") + }) +} diff --git a/net/ghttp/internal/client/client.go b/net/ghttp/internal/client/client.go index 3aba87d94..6c2b292b1 100644 --- a/net/ghttp/internal/client/client.go +++ b/net/ghttp/internal/client/client.go @@ -27,7 +27,6 @@ type Client struct { http.Client // Underlying HTTP Client. ctx context.Context // Context for each request. dump bool // Mark this request will be dumped. - agent string // Client agent. parent *Client // Parent http client, this is used for chaining operations. header map[string]string // Custom header map. cookies map[string]string // Custom cookie map. @@ -46,7 +45,7 @@ var ( // New creates and returns a new HTTP client object. func New() *Client { - return &Client{ + client := &Client{ Client: http.Client{ Transport: &http.Transport{ // No validation for https certification of the server in default. @@ -58,11 +57,12 @@ func New() *Client { }, header: make(map[string]string), cookies: make(map[string]string), - agent: defaultClientAgent, } + client.header["User-Agent"] = defaultClientAgent + return client } -// Clone clones current client and returns a new one. +// Clone deeply clones current client and returns a new one. func (c *Client) Clone() *Client { newClient := New() *newClient = *c diff --git a/net/ghttp/internal/client/client_request.go b/net/ghttp/internal/client/client_request.go index f74ec6042..03673a66d 100644 --- a/net/ghttp/internal/client/client_request.go +++ b/net/ghttp/internal/client/client_request.go @@ -251,10 +251,6 @@ func (c *Client) prepareRequest(method, url string, data ...interface{}) (req *h } else { req = req.WithContext(context.Background()) } - // Client agent. - if c.agent != "" { - req.Header.Set("User-Agent", c.agent) - } // Custom header. if len(c.header) > 0 { for k, v := range c.header {