This commit is contained in:
John Guo
2021-01-30 23:05:02 +08:00
parent 13248d6736
commit 3e33d66ab4
3 changed files with 24 additions and 8 deletions

View File

@ -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")
})
}

View File

@ -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

View File

@ -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 {