[TOC]
GF
框架的客户端支持便捷的链式操作,常用方法如下:
func (c *Client) Ctx(ctx context.Context) *Client
func (c *Client) Timeout(t time.Duration) *Client
func (c *Client) Cookie(m map[string]string) *Client
func (c *Client) Header(m map[string]string) *Client
func (c *Client) HeaderRaw(headers string) *Client
func (c *Client) ContentType(contentType string) *Client
func (c *Client) ContentJson() *Client
func (c *Client) ContentXml() *Client
func (c *Client) BasicAuth(user, pass string) *Client
简要说明:
Timeout
方法用于设置当前请求超时时间。Ctx
方法用于设置当前请求的上下文对象context.Context
。Cookie
方法用于设置当前请求的自定义Cookie
信息。Header*
方法用于设置当前请求的自定义Header
信息。Content*
方法用于设置当前请求的Content-Type
信息,并且支持根据该信息自动检查提交参数并自动编码。BasicAuth
方法用于设置HTTP Basic Auth
校验信息。
g.Client().Timeout(3*time.Second).GetContent("http://user.svc/v1/user/info/1")
g.Client().Timeout(10*time.Second).PostContent("http://order.svc/v1/order/create", g.Map{
"uid" : 1,
"sku_id" : 10000,
"amount" : 19.99,
"create_time" : "2020-03-26 12:00:00",
})
g.Client().Cookie("sessionid", "MNV5432PIY76").GetContent("http://user.svc/v1/user/info/1")
g.Client().Header("Trace-Id", "XVF654RT98UJNMN641V06Y").GetContent("http://user.svc/v1/user/info/1")
g.Client().HeaderRaw(`
Referer: https://goframe.org/
User-Agent: MyTesyClient
`).GetContent("http://user.svc/v1/user/info")
g.Client().ContentJson().PostContent("http://order.svc/v1/order/create", g.Map{
"uid" : 1,
"sku_id" : 10000,
"amount" : 19.99,
"create_time" : "2020-03-26 12:00:00",
})
该请求将会将Content-Type
设置为application/json
,并且将提交参数自动编码为Json
:
{"uid":1,"sku_id":10000,"amount":19.99,"create_time":"2020-03-26 12:00:00"}
g.Client().ContentXml().PostContent("http://order.svc/v1/order/create", g.Map{
"uid" : 1,
"sku_id" : 10000,
"amount" : 19.99,
"create_time" : "2020-03-26 12:00:00",
})
该请求将会将Content-Type
设置为application/xml
,并且将提交参数自动编码为Xml
:
<doc><amount>19.99</amount><create_time>2020-03-26 12:00:00</create_time><sku_id>10000</sku_id><uid>1</uid></doc>