1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-23 11:20:57 +00:00
Beego/httplib/httplib.go

447 lines
11 KiB
Go
Raw Normal View History

2014-04-12 05:18:18 +00:00
// Beego (http://beego.me/)
2014-07-03 15:40:21 +00:00
//
2014-04-12 05:18:18 +00:00
// @description beego is an open-source, high-performance web framework for the Go programming language.
2014-07-03 15:40:21 +00:00
//
2014-04-12 05:18:18 +00:00
// @link http://github.com/astaxie/beego for the canonical source repository
2014-07-03 15:40:21 +00:00
//
2014-04-12 05:18:18 +00:00
// @license http://github.com/astaxie/beego/blob/master/LICENSE
2014-07-03 15:40:21 +00:00
//
2014-04-12 05:18:18 +00:00
// @authors astaxie
package httplib
2013-08-03 14:20:09 +00:00
import (
"bytes"
2013-12-10 14:01:50 +00:00
"crypto/tls"
2013-08-03 14:20:09 +00:00
"encoding/json"
"encoding/xml"
"io"
"io/ioutil"
2014-05-08 08:58:08 +00:00
"mime/multipart"
2013-08-03 14:20:09 +00:00
"net"
"net/http"
"net/http/cookiejar"
"net/http/httputil"
2013-08-03 14:20:09 +00:00
"net/url"
"os"
"strings"
"sync"
"time"
2013-08-03 14:20:09 +00:00
)
var defaultSetting = BeegoHttpSettings{false, "beegoServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false}
var defaultCookieJar http.CookieJar
var settingMutex sync.Mutex
// createDefaultCookieJar creates a global cookiejar to store cookies.
func createDefaultCookie() {
settingMutex.Lock()
defer settingMutex.Unlock()
defaultCookieJar, _ = cookiejar.New(nil)
}
// Overwrite default settings
func SetDefaultSetting(setting BeegoHttpSettings) {
settingMutex.Lock()
defer settingMutex.Unlock()
defaultSetting = setting
if defaultSetting.ConnectTimeout == 0 {
defaultSetting.ConnectTimeout = 60 * time.Second
}
if defaultSetting.ReadWriteTimeout == 0 {
defaultSetting.ReadWriteTimeout = 60 * time.Second
}
}
2013-08-03 14:20:09 +00:00
2013-12-27 09:11:39 +00:00
// Get returns *BeegoHttpRequest with GET method.
2013-08-03 14:20:09 +00:00
func Get(url string) *BeegoHttpRequest {
var req http.Request
req.Method = "GET"
req.Header = http.Header{}
return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting}
2013-08-03 14:20:09 +00:00
}
2013-12-27 09:11:39 +00:00
// Post returns *BeegoHttpRequest with POST method.
2013-08-03 14:20:09 +00:00
func Post(url string) *BeegoHttpRequest {
var req http.Request
req.Method = "POST"
req.Header = http.Header{}
return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting}
2013-08-03 14:20:09 +00:00
}
2013-12-27 09:11:39 +00:00
// Put returns *BeegoHttpRequest with PUT method.
2013-08-03 14:20:09 +00:00
func Put(url string) *BeegoHttpRequest {
var req http.Request
req.Method = "PUT"
req.Header = http.Header{}
return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting}
2013-08-03 14:20:09 +00:00
}
2013-12-27 09:11:39 +00:00
// Delete returns *BeegoHttpRequest DELETE GET method.
2013-08-03 14:20:09 +00:00
func Delete(url string) *BeegoHttpRequest {
var req http.Request
req.Method = "DELETE"
req.Header = http.Header{}
return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting}
2013-08-03 14:20:09 +00:00
}
2013-12-27 09:11:39 +00:00
// Head returns *BeegoHttpRequest with HEAD method.
2013-08-03 14:20:09 +00:00
func Head(url string) *BeegoHttpRequest {
var req http.Request
req.Method = "HEAD"
req.Header = http.Header{}
return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting}
}
// BeegoHttpSettings
type BeegoHttpSettings struct {
ShowDebug bool
UserAgent string
ConnectTimeout time.Duration
ReadWriteTimeout time.Duration
TlsClientConfig *tls.Config
Proxy func(*http.Request) (*url.URL, error)
Transport http.RoundTripper
EnableCookie bool
2013-08-03 14:20:09 +00:00
}
2013-12-27 09:11:39 +00:00
// BeegoHttpRequest provides more useful methods for requesting one url than http.Request.
2013-08-03 14:20:09 +00:00
type BeegoHttpRequest struct {
url string
req *http.Request
params map[string]string
files map[string]string
setting BeegoHttpSettings
}
// Change request settings
func (b *BeegoHttpRequest) Setting(setting BeegoHttpSettings) *BeegoHttpRequest {
b.setting = setting
return b
}
// SetEnableCookie sets enable/disable cookiejar
func (b *BeegoHttpRequest) SetEnableCookie(enable bool) *BeegoHttpRequest {
b.setting.EnableCookie = enable
return b
}
// SetUserAgent sets User-Agent header field
func (b *BeegoHttpRequest) SetAgent(useragent string) *BeegoHttpRequest {
b.setting.UserAgent = useragent
return b
2013-08-03 14:20:09 +00:00
}
2013-12-27 09:11:39 +00:00
// Debug sets show debug or not when executing request.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) Debug(isdebug bool) *BeegoHttpRequest {
b.setting.ShowDebug = isdebug
2013-08-03 14:20:09 +00:00
return b
}
2013-12-27 09:11:39 +00:00
// SetTimeout sets connect time out and read-write time out for BeegoRequest.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *BeegoHttpRequest {
b.setting.ConnectTimeout = connectTimeout
b.setting.ReadWriteTimeout = readWriteTimeout
2013-08-03 14:20:09 +00:00
return b
}
2013-12-27 09:11:39 +00:00
// SetTLSClientConfig sets tls connection configurations if visiting https url.
2013-12-10 14:01:50 +00:00
func (b *BeegoHttpRequest) SetTLSClientConfig(config *tls.Config) *BeegoHttpRequest {
b.setting.TlsClientConfig = config
2013-12-10 14:01:50 +00:00
return b
}
2013-12-27 09:11:39 +00:00
// Header add header item string in request.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) Header(key, value string) *BeegoHttpRequest {
b.req.Header.Set(key, value)
return b
}
// Set the protocol version for incoming requests.
// Client requests always use HTTP/1.1.
func (b *BeegoHttpRequest) SetProtocolVersion(vers string) *BeegoHttpRequest {
if len(vers) == 0 {
vers = "HTTP/1.1"
}
major, minor, ok := http.ParseHTTPVersion(vers)
if ok {
b.req.Proto = vers
b.req.ProtoMajor = major
b.req.ProtoMinor = minor
}
return b
}
2013-12-27 09:11:39 +00:00
// SetCookie add cookie into request.
2013-12-12 07:23:17 +00:00
func (b *BeegoHttpRequest) SetCookie(cookie *http.Cookie) *BeegoHttpRequest {
b.req.Header.Add("Cookie", cookie.String())
2013-12-12 07:23:17 +00:00
return b
}
// Set transport to
func (b *BeegoHttpRequest) SetTransport(transport http.RoundTripper) *BeegoHttpRequest {
b.setting.Transport = transport
return b
}
// Set http proxy
// example:
//
// func(req *http.Request) (*url.URL, error) {
// u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
// return u, nil
// }
func (b *BeegoHttpRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHttpRequest {
b.setting.Proxy = proxy
return b
}
2013-12-27 09:11:39 +00:00
// Param adds query param in to request.
// params build query string as ?key1=value1&key2=value2...
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) Param(key, value string) *BeegoHttpRequest {
b.params[key] = value
return b
}
2014-05-08 08:58:08 +00:00
func (b *BeegoHttpRequest) PostFile(formname, filename string) *BeegoHttpRequest {
b.files[formname] = filename
return b
}
2013-12-27 09:11:39 +00:00
// Body adds request raw body.
// it supports string and []byte.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest {
switch t := data.(type) {
case string:
bf := bytes.NewBufferString(t)
b.req.Body = ioutil.NopCloser(bf)
b.req.ContentLength = int64(len(t))
case []byte:
bf := bytes.NewBuffer(t)
b.req.Body = ioutil.NopCloser(bf)
b.req.ContentLength = int64(len(t))
}
return b
}
func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
var paramBody string
if len(b.params) > 0 {
2013-08-03 14:20:09 +00:00
var buf bytes.Buffer
for k, v := range b.params {
buf.WriteString(url.QueryEscape(k))
buf.WriteByte('=')
buf.WriteString(url.QueryEscape(v))
buf.WriteByte('&')
}
paramBody = buf.String()
paramBody = paramBody[0 : len(paramBody)-1]
}
2013-08-03 14:20:09 +00:00
if b.req.Method == "GET" && len(paramBody) > 0 {
if strings.Index(b.url, "?") != -1 {
b.url += "&" + paramBody
2013-08-03 14:20:09 +00:00
} else {
b.url = b.url + "?" + paramBody
2013-08-03 14:20:09 +00:00
}
} else if b.req.Method == "POST" && b.req.Body == nil && len(paramBody) > 0 {
2014-05-08 08:58:08 +00:00
if len(b.files) > 0 {
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
for formname, filename := range b.files {
fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
if err != nil {
return nil, err
}
fh, err := os.Open(filename)
if err != nil {
return nil, err
}
//iocopy
_, err = io.Copy(fileWriter, fh)
fh.Close()
if err != nil {
return nil, err
}
}
for k, v := range b.params {
bodyWriter.WriteField(k, v)
}
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
b.Header("Content-Type", contentType)
b.req.Body = ioutil.NopCloser(bodyBuf)
b.req.ContentLength = int64(bodyBuf.Len())
} else {
b.Header("Content-Type", "application/x-www-form-urlencoded")
b.Body(paramBody)
}
2013-08-03 14:20:09 +00:00
}
url, err := url.Parse(b.url)
if url.Scheme == "" {
b.url = "http://" + b.url
2013-08-03 14:20:09 +00:00
url, err = url.Parse(b.url)
}
if err != nil {
return nil, err
}
2013-08-03 14:20:09 +00:00
b.req.URL = url
if b.setting.ShowDebug {
2013-08-03 14:20:09 +00:00
dump, err := httputil.DumpRequest(b.req, true)
if err != nil {
println(err.Error())
}
println(string(dump))
}
trans := b.setting.Transport
if trans == nil {
// create default transport
trans = &http.Transport{
TLSClientConfig: b.setting.TlsClientConfig,
Proxy: b.setting.Proxy,
Dial: TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout),
}
} else {
// if b.transport is *http.Transport then set the settings.
if t, ok := trans.(*http.Transport); ok {
if t.TLSClientConfig == nil {
t.TLSClientConfig = b.setting.TlsClientConfig
}
if t.Proxy == nil {
t.Proxy = b.setting.Proxy
}
if t.Dial == nil {
t.Dial = TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout)
}
}
2013-08-03 14:20:09 +00:00
}
var jar http.CookieJar
if b.setting.EnableCookie {
if defaultCookieJar == nil {
createDefaultCookie()
}
jar = defaultCookieJar
} else {
jar = nil
}
client := &http.Client{
Transport: trans,
Jar: jar,
}
if b.setting.UserAgent != "" {
b.req.Header.Set("User-Agent", b.setting.UserAgent)
}
2013-08-03 14:20:09 +00:00
resp, err := client.Do(b.req)
if err != nil {
return nil, err
}
return resp, nil
}
2013-12-27 09:11:39 +00:00
// String returns the body string in response.
// it calls Response inner.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) String() (string, error) {
data, err := b.Bytes()
if err != nil {
return "", err
}
return string(data), nil
}
2013-12-27 09:11:39 +00:00
// Bytes returns the body []byte in response.
// it calls Response inner.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) Bytes() ([]byte, error) {
resp, err := b.getResponse()
if err != nil {
return nil, err
}
if resp.Body == nil {
return nil, nil
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return data, nil
}
2013-12-27 09:11:39 +00:00
// ToFile saves the body data in response to one file.
// it calls Response inner.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) ToFile(filename string) error {
f, err := os.Create(filename)
if err != nil {
return err
}
defer f.Close()
resp, err := b.getResponse()
if err != nil {
return err
}
if resp.Body == nil {
return nil
}
defer resp.Body.Close()
_, err = io.Copy(f, resp.Body)
if err != nil {
return err
}
return nil
}
2013-12-27 09:11:39 +00:00
// ToJson returns the map that marshals from the body bytes as json in response .
// it calls Response inner.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) ToJson(v interface{}) error {
data, err := b.Bytes()
if err != nil {
return err
}
err = json.Unmarshal(data, v)
if err != nil {
return err
}
return nil
}
2013-12-27 09:11:39 +00:00
// ToXml returns the map that marshals from the body bytes as xml in response .
// it calls Response inner.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) ToXML(v interface{}) error {
data, err := b.Bytes()
if err != nil {
return err
}
err = xml.Unmarshal(data, v)
if err != nil {
return err
}
return nil
}
2013-12-27 09:11:39 +00:00
// Response executes request client gets response mannually.
2013-08-03 14:20:09 +00:00
func (b *BeegoHttpRequest) Response() (*http.Response, error) {
return b.getResponse()
}
2013-12-27 09:11:39 +00:00
// TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.
2013-08-03 14:20:09 +00:00
func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
return func(netw, addr string) (net.Conn, error) {
conn, err := net.DialTimeout(netw, addr, cTimeout)
if err != nil {
return nil, err
}
conn.SetDeadline(time.Now().Add(rwTimeout))
return conn, nil
}
}