ghttp.Client增加HTTP账号密码验证功能

This commit is contained in:
John
2018-07-23 11:16:21 +08:00
parent ec4b96aa7c
commit b6917db8e6

View File

@ -19,19 +19,21 @@ import (
// http客户端
type Client struct {
http.Client // 底层http client对象
header map[string]string // header
http.Client // 底层http client对象
header map[string]string // header
authUser string // HTTP基本权限设置名称
authPass string // HTTP基本权限设置密码
}
// http客户端对象指针
func NewClient() (*Client) {
return &Client{
http.Client {
Client : http.Client {
Transport: &http.Transport {
DisableKeepAlives: true,
},
},
make(map[string]string),
header : make(map[string]string),
}
}
@ -45,6 +47,12 @@ func (c *Client) SetTimeOut(t time.Duration) {
c.Timeout = t
}
// 设置HTTP访问账号密码
func (c *Client) SetBasicAuth(user, pass string) {
c.authUser = user
c.authPass = pass
}
// GET请求
func (c *Client) Get(url string) (*ClientResponse, error) {
return c.DoRequest("GET", url, []byte(""))
@ -102,6 +110,10 @@ func (c *Client) Post(url, data string) (*ClientResponse, error) {
req.Header.Set(k, v)
}
}
// HTTP账号密码
if len(c.authUser) > 0 {
req.SetBasicAuth(c.authUser, c.authPass)
}
// 执行请求
resp, err := c.Do(req)
if err != nil {