1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-26 03:01:28 +00:00

golint httplib

This commit is contained in:
astaxie 2015-09-11 22:28:28 +08:00
parent 65fb7ce391
commit 657995092a
2 changed files with 70 additions and 67 deletions

View File

@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
// Package httplib is used as http.Client
// Usage: // Usage:
// //
// import "github.com/astaxie/beego/httplib" // import "github.com/astaxie/beego/httplib"
@ -51,7 +52,7 @@ import (
"time" "time"
) )
var defaultSetting = BeegoHttpSettings{ var defaultSetting = BeegoHTTPSettings{
UserAgent: "beegoServer", UserAgent: "beegoServer",
ConnectTimeout: 60 * time.Second, ConnectTimeout: 60 * time.Second,
ReadWriteTimeout: 60 * time.Second, ReadWriteTimeout: 60 * time.Second,
@ -69,15 +70,15 @@ func createDefaultCookie() {
defaultCookieJar, _ = cookiejar.New(nil) defaultCookieJar, _ = cookiejar.New(nil)
} }
// Overwrite default settings // SetDefaultSetting Overwrite default settings
func SetDefaultSetting(setting BeegoHttpSettings) { func SetDefaultSetting(setting BeegoHTTPSettings) {
settingMutex.Lock() settingMutex.Lock()
defer settingMutex.Unlock() defer settingMutex.Unlock()
defaultSetting = setting defaultSetting = setting
} }
// return *BeegoHttpRequest with specific method // NewBeegoRequest return *BeegoHttpRequest with specific method
func NewBeegoRequest(rawurl, method string) *BeegoHttpRequest { func NewBeegoRequest(rawurl, method string) *BeegoHTTPRequest {
var resp http.Response var resp http.Response
u, err := url.Parse(rawurl) u, err := url.Parse(rawurl)
if err != nil { if err != nil {
@ -91,7 +92,7 @@ func NewBeegoRequest(rawurl, method string) *BeegoHttpRequest {
ProtoMajor: 1, ProtoMajor: 1,
ProtoMinor: 1, ProtoMinor: 1,
} }
return &BeegoHttpRequest{ return &BeegoHTTPRequest{
url: rawurl, url: rawurl,
req: &req, req: &req,
params: map[string][]string{}, params: map[string][]string{},
@ -102,37 +103,37 @@ func NewBeegoRequest(rawurl, method string) *BeegoHttpRequest {
} }
// Get returns *BeegoHttpRequest with GET method. // Get returns *BeegoHttpRequest with GET method.
func Get(url string) *BeegoHttpRequest { func Get(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "GET") return NewBeegoRequest(url, "GET")
} }
// Post returns *BeegoHttpRequest with POST method. // Post returns *BeegoHttpRequest with POST method.
func Post(url string) *BeegoHttpRequest { func Post(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "POST") return NewBeegoRequest(url, "POST")
} }
// Put returns *BeegoHttpRequest with PUT method. // Put returns *BeegoHttpRequest with PUT method.
func Put(url string) *BeegoHttpRequest { func Put(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "PUT") return NewBeegoRequest(url, "PUT")
} }
// Delete returns *BeegoHttpRequest DELETE method. // Delete returns *BeegoHttpRequest DELETE method.
func Delete(url string) *BeegoHttpRequest { func Delete(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "DELETE") return NewBeegoRequest(url, "DELETE")
} }
// Head returns *BeegoHttpRequest with HEAD method. // Head returns *BeegoHttpRequest with HEAD method.
func Head(url string) *BeegoHttpRequest { func Head(url string) *BeegoHTTPRequest {
return NewBeegoRequest(url, "HEAD") return NewBeegoRequest(url, "HEAD")
} }
// BeegoHttpSettings // BeegoHTTPSettings is the http.Client setting
type BeegoHttpSettings struct { type BeegoHTTPSettings struct {
ShowDebug bool ShowDebug bool
UserAgent string UserAgent string
ConnectTimeout time.Duration ConnectTimeout time.Duration
ReadWriteTimeout time.Duration ReadWriteTimeout time.Duration
TlsClientConfig *tls.Config TLSClientConfig *tls.Config
Proxy func(*http.Request) (*url.URL, error) Proxy func(*http.Request) (*url.URL, error)
Transport http.RoundTripper Transport http.RoundTripper
EnableCookie bool EnableCookie bool
@ -140,92 +141,92 @@ type BeegoHttpSettings struct {
DumpBody bool DumpBody bool
} }
// BeegoHttpRequest provides more useful methods for requesting one url than http.Request. // BeegoHTTPRequest provides more useful methods for requesting one url than http.Request.
type BeegoHttpRequest struct { type BeegoHTTPRequest struct {
url string url string
req *http.Request req *http.Request
params map[string][]string params map[string][]string
files map[string]string files map[string]string
setting BeegoHttpSettings setting BeegoHTTPSettings
resp *http.Response resp *http.Response
body []byte body []byte
dump []byte dump []byte
} }
// get request // GetRequest return the request object
func (b *BeegoHttpRequest) GetRequest() *http.Request { func (b *BeegoHTTPRequest) GetRequest() *http.Request {
return b.req return b.req
} }
// Change request settings // Setting Change request settings
func (b *BeegoHttpRequest) Setting(setting BeegoHttpSettings) *BeegoHttpRequest { func (b *BeegoHTTPRequest) Setting(setting BeegoHTTPSettings) *BeegoHTTPRequest {
b.setting = setting b.setting = setting
return b return b
} }
// SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password. // SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
func (b *BeegoHttpRequest) SetBasicAuth(username, password string) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetBasicAuth(username, password string) *BeegoHTTPRequest {
b.req.SetBasicAuth(username, password) b.req.SetBasicAuth(username, password)
return b return b
} }
// SetEnableCookie sets enable/disable cookiejar // SetEnableCookie sets enable/disable cookiejar
func (b *BeegoHttpRequest) SetEnableCookie(enable bool) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetEnableCookie(enable bool) *BeegoHTTPRequest {
b.setting.EnableCookie = enable b.setting.EnableCookie = enable
return b return b
} }
// SetUserAgent sets User-Agent header field // SetUserAgent sets User-Agent header field
func (b *BeegoHttpRequest) SetUserAgent(useragent string) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetUserAgent(useragent string) *BeegoHTTPRequest {
b.setting.UserAgent = useragent b.setting.UserAgent = useragent
return b return b
} }
// Debug sets show debug or not when executing request. // Debug sets show debug or not when executing request.
func (b *BeegoHttpRequest) Debug(isdebug bool) *BeegoHttpRequest { func (b *BeegoHTTPRequest) Debug(isdebug bool) *BeegoHTTPRequest {
b.setting.ShowDebug = isdebug b.setting.ShowDebug = isdebug
return b return b
} }
// Dump Body. // DumpBody setting whether need to Dump the Body.
func (b *BeegoHttpRequest) DumpBody(isdump bool) *BeegoHttpRequest { func (b *BeegoHTTPRequest) DumpBody(isdump bool) *BeegoHTTPRequest {
b.setting.DumpBody = isdump b.setting.DumpBody = isdump
return b return b
} }
// return the DumpRequest // DumpRequest return the DumpRequest
func (b *BeegoHttpRequest) DumpRequest() []byte { func (b *BeegoHTTPRequest) DumpRequest() []byte {
return b.dump return b.dump
} }
// SetTimeout sets connect time out and read-write time out for BeegoRequest. // SetTimeout sets connect time out and read-write time out for BeegoRequest.
func (b *BeegoHttpRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *BeegoHTTPRequest {
b.setting.ConnectTimeout = connectTimeout b.setting.ConnectTimeout = connectTimeout
b.setting.ReadWriteTimeout = readWriteTimeout b.setting.ReadWriteTimeout = readWriteTimeout
return b return b
} }
// SetTLSClientConfig sets tls connection configurations if visiting https url. // SetTLSClientConfig sets tls connection configurations if visiting https url.
func (b *BeegoHttpRequest) SetTLSClientConfig(config *tls.Config) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetTLSClientConfig(config *tls.Config) *BeegoHTTPRequest {
b.setting.TlsClientConfig = config b.setting.TLSClientConfig = config
return b return b
} }
// Header add header item string in request. // Header add header item string in request.
func (b *BeegoHttpRequest) Header(key, value string) *BeegoHttpRequest { func (b *BeegoHTTPRequest) Header(key, value string) *BeegoHTTPRequest {
b.req.Header.Set(key, value) b.req.Header.Set(key, value)
return b return b
} }
// Set HOST // SetHost set the request host
func (b *BeegoHttpRequest) SetHost(host string) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetHost(host string) *BeegoHTTPRequest {
b.req.Host = host b.req.Host = host
return b return b
} }
// Set the protocol version for incoming requests. // SetProtocolVersion Set the protocol version for incoming requests.
// Client requests always use HTTP/1.1. // Client requests always use HTTP/1.1.
func (b *BeegoHttpRequest) SetProtocolVersion(vers string) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetProtocolVersion(vers string) *BeegoHTTPRequest {
if len(vers) == 0 { if len(vers) == 0 {
vers = "HTTP/1.1" vers = "HTTP/1.1"
} }
@ -241,32 +242,32 @@ func (b *BeegoHttpRequest) SetProtocolVersion(vers string) *BeegoHttpRequest {
} }
// SetCookie add cookie into request. // SetCookie add cookie into request.
func (b *BeegoHttpRequest) SetCookie(cookie *http.Cookie) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetCookie(cookie *http.Cookie) *BeegoHTTPRequest {
b.req.Header.Add("Cookie", cookie.String()) b.req.Header.Add("Cookie", cookie.String())
return b return b
} }
// Set transport to // SetTransport set the setting transport
func (b *BeegoHttpRequest) SetTransport(transport http.RoundTripper) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetTransport(transport http.RoundTripper) *BeegoHTTPRequest {
b.setting.Transport = transport b.setting.Transport = transport
return b return b
} }
// Set http proxy // SetProxy set the http proxy
// example: // example:
// //
// func(req *http.Request) (*url.URL, error) { // func(req *http.Request) (*url.URL, error) {
// u, _ := url.ParseRequestURI("http://127.0.0.1:8118") // u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
// return u, nil // return u, nil
// } // }
func (b *BeegoHttpRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHttpRequest { func (b *BeegoHTTPRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHTTPRequest {
b.setting.Proxy = proxy b.setting.Proxy = proxy
return b return b
} }
// Param adds query param in to request. // Param adds query param in to request.
// params build query string as ?key1=value1&key2=value2... // params build query string as ?key1=value1&key2=value2...
func (b *BeegoHttpRequest) Param(key, value string) *BeegoHttpRequest { func (b *BeegoHTTPRequest) Param(key, value string) *BeegoHTTPRequest {
if param, ok := b.params[key]; ok { if param, ok := b.params[key]; ok {
b.params[key] = append(param, value) b.params[key] = append(param, value)
} else { } else {
@ -275,14 +276,15 @@ func (b *BeegoHttpRequest) Param(key, value string) *BeegoHttpRequest {
return b return b
} }
func (b *BeegoHttpRequest) PostFile(formname, filename string) *BeegoHttpRequest { // PostFile add a post file to the request
func (b *BeegoHTTPRequest) PostFile(formname, filename string) *BeegoHTTPRequest {
b.files[formname] = filename b.files[formname] = filename
return b return b
} }
// Body adds request raw body. // Body adds request raw body.
// it supports string and []byte. // it supports string and []byte.
func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest { func (b *BeegoHTTPRequest) Body(data interface{}) *BeegoHTTPRequest {
switch t := data.(type) { switch t := data.(type) {
case string: case string:
bf := bytes.NewBufferString(t) bf := bytes.NewBufferString(t)
@ -296,8 +298,8 @@ func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest {
return b return b
} }
// JsonBody adds request raw body encoding by JSON. // JSONBody adds request raw body encoding by JSON.
func (b *BeegoHttpRequest) JsonBody(obj interface{}) (*BeegoHttpRequest, error) { func (b *BeegoHTTPRequest) JSONBody(obj interface{}) (*BeegoHTTPRequest, error) {
if b.req.Body == nil && obj != nil { if b.req.Body == nil && obj != nil {
buf := bytes.NewBuffer(nil) buf := bytes.NewBuffer(nil)
enc := json.NewEncoder(buf) enc := json.NewEncoder(buf)
@ -311,7 +313,7 @@ func (b *BeegoHttpRequest) JsonBody(obj interface{}) (*BeegoHttpRequest, error)
return b, nil return b, nil
} }
func (b *BeegoHttpRequest) buildUrl(paramBody string) { func (b *BeegoHTTPRequest) buildURL(paramBody string) {
// build GET url with query string // build GET url with query string
if b.req.Method == "GET" && len(paramBody) > 0 { if b.req.Method == "GET" && len(paramBody) > 0 {
if strings.Index(b.url, "?") != -1 { if strings.Index(b.url, "?") != -1 {
@ -366,11 +368,11 @@ func (b *BeegoHttpRequest) buildUrl(paramBody string) {
} }
} }
func (b *BeegoHttpRequest) getResponse() (*http.Response, error) { func (b *BeegoHTTPRequest) getResponse() (*http.Response, error) {
if b.resp.StatusCode != 0 { if b.resp.StatusCode != 0 {
return b.resp, nil return b.resp, nil
} }
resp, err := b.SendOut() resp, err := b.DoRequest()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -378,7 +380,8 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
return resp, nil return resp, nil
} }
func (b *BeegoHttpRequest) SendOut() (*http.Response, error) { // DoRequest will do the client.Do
func (b *BeegoHTTPRequest) DoRequest() (*http.Response, error) {
var paramBody string var paramBody string
if len(b.params) > 0 { if len(b.params) > 0 {
var buf bytes.Buffer var buf bytes.Buffer
@ -394,7 +397,7 @@ func (b *BeegoHttpRequest) SendOut() (*http.Response, error) {
paramBody = paramBody[0 : len(paramBody)-1] paramBody = paramBody[0 : len(paramBody)-1]
} }
b.buildUrl(paramBody) b.buildURL(paramBody)
url, err := url.Parse(b.url) url, err := url.Parse(b.url)
if err != nil { if err != nil {
return nil, err return nil, err
@ -407,7 +410,7 @@ func (b *BeegoHttpRequest) SendOut() (*http.Response, error) {
if trans == nil { if trans == nil {
// create default transport // create default transport
trans = &http.Transport{ trans = &http.Transport{
TLSClientConfig: b.setting.TlsClientConfig, TLSClientConfig: b.setting.TLSClientConfig,
Proxy: b.setting.Proxy, Proxy: b.setting.Proxy,
Dial: TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout), Dial: TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout),
} }
@ -415,7 +418,7 @@ func (b *BeegoHttpRequest) SendOut() (*http.Response, error) {
// if b.transport is *http.Transport then set the settings. // if b.transport is *http.Transport then set the settings.
if t, ok := trans.(*http.Transport); ok { if t, ok := trans.(*http.Transport); ok {
if t.TLSClientConfig == nil { if t.TLSClientConfig == nil {
t.TLSClientConfig = b.setting.TlsClientConfig t.TLSClientConfig = b.setting.TLSClientConfig
} }
if t.Proxy == nil { if t.Proxy == nil {
t.Proxy = b.setting.Proxy t.Proxy = b.setting.Proxy
@ -426,7 +429,7 @@ func (b *BeegoHttpRequest) SendOut() (*http.Response, error) {
} }
} }
var jar http.CookieJar = nil var jar http.CookieJar
if b.setting.EnableCookie { if b.setting.EnableCookie {
if defaultCookieJar == nil { if defaultCookieJar == nil {
createDefaultCookie() createDefaultCookie()
@ -455,7 +458,7 @@ func (b *BeegoHttpRequest) SendOut() (*http.Response, error) {
// String returns the body string in response. // String returns the body string in response.
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) String() (string, error) { func (b *BeegoHTTPRequest) String() (string, error) {
data, err := b.Bytes() data, err := b.Bytes()
if err != nil { if err != nil {
return "", err return "", err
@ -466,7 +469,7 @@ func (b *BeegoHttpRequest) String() (string, error) {
// Bytes returns the body []byte in response. // Bytes returns the body []byte in response.
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) Bytes() ([]byte, error) { func (b *BeegoHTTPRequest) Bytes() ([]byte, error) {
if b.body != nil { if b.body != nil {
return b.body, nil return b.body, nil
} }
@ -492,7 +495,7 @@ func (b *BeegoHttpRequest) Bytes() ([]byte, error) {
// ToFile saves the body data in response to one file. // ToFile saves the body data in response to one file.
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) ToFile(filename string) error { func (b *BeegoHTTPRequest) ToFile(filename string) error {
f, err := os.Create(filename) f, err := os.Create(filename)
if err != nil { if err != nil {
return err return err
@ -511,9 +514,9 @@ func (b *BeegoHttpRequest) ToFile(filename string) error {
return err return err
} }
// ToJson returns the map that marshals from the body bytes as json in response . // ToJSON returns the map that marshals from the body bytes as json in response .
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) ToJson(v interface{}) error { func (b *BeegoHTTPRequest) ToJSON(v interface{}) error {
data, err := b.Bytes() data, err := b.Bytes()
if err != nil { if err != nil {
return err return err
@ -521,9 +524,9 @@ func (b *BeegoHttpRequest) ToJson(v interface{}) error {
return json.Unmarshal(data, v) return json.Unmarshal(data, v)
} }
// ToXml returns the map that marshals from the body bytes as xml in response . // ToXML returns the map that marshals from the body bytes as xml in response .
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) ToXml(v interface{}) error { func (b *BeegoHTTPRequest) ToXML(v interface{}) error {
data, err := b.Bytes() data, err := b.Bytes()
if err != nil { if err != nil {
return err return err
@ -532,7 +535,7 @@ func (b *BeegoHttpRequest) ToXml(v interface{}) error {
} }
// Response executes request client gets response mannually. // Response executes request client gets response mannually.
func (b *BeegoHttpRequest) Response() (*http.Response, error) { func (b *BeegoHTTPRequest) Response() (*http.Response, error) {
return b.getResponse() return b.getResponse()
} }

View File

@ -150,7 +150,7 @@ func TestWithUserAgent(t *testing.T) {
func TestWithSetting(t *testing.T) { func TestWithSetting(t *testing.T) {
v := "beego" v := "beego"
var setting BeegoHttpSettings var setting BeegoHTTPSettings
setting.EnableCookie = true setting.EnableCookie = true
setting.UserAgent = v setting.UserAgent = v
setting.Transport = nil setting.Transport = nil
@ -178,11 +178,11 @@ func TestToJson(t *testing.T) {
t.Log(resp) t.Log(resp)
// httpbin will return http remote addr // httpbin will return http remote addr
type Ip struct { type IP struct {
Origin string `json:"origin"` Origin string `json:"origin"`
} }
var ip Ip var ip IP
err = req.ToJson(&ip) err = req.ToJSON(&ip)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }