httplib.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. // Copyright 2015 bat authors
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. // Usage:
  16. //
  17. // import "github.com/astaxie/beego/httplib"
  18. //
  19. // b := httplib.Post("http://beego.me/")
  20. // b.Param("username","astaxie")
  21. // b.Param("password","123456")
  22. // b.PostFile("uploadfile1", "httplib.pdf")
  23. // b.PostFile("uploadfile2", "httplib.txt")
  24. // str, err := b.String()
  25. // if err != nil {
  26. // t.Fatal(err)
  27. // }
  28. // fmt.Println(str)
  29. //
  30. // more docs http://beego.me/docs/module/httplib.md
  31. package httplib
  32. import (
  33. "bytes"
  34. "compress/gzip"
  35. "crypto/tls"
  36. "encoding/json"
  37. "encoding/xml"
  38. "io"
  39. "io/ioutil"
  40. "log"
  41. "mime/multipart"
  42. "net"
  43. "net/http"
  44. "net/http/cookiejar"
  45. "net/http/httputil"
  46. "net/url"
  47. "os"
  48. "strings"
  49. "sync"
  50. "time"
  51. )
  52. var defaultSetting = BeegoHttpSettings{false, "beegoServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false, true, true}
  53. var defaultCookieJar http.CookieJar
  54. var settingMutex sync.Mutex
  55. // createDefaultCookie creates a global cookiejar to store cookies.
  56. func createDefaultCookie() {
  57. settingMutex.Lock()
  58. defer settingMutex.Unlock()
  59. defaultCookieJar, _ = cookiejar.New(nil)
  60. }
  61. // Overwrite default settings
  62. func SetDefaultSetting(setting BeegoHttpSettings) {
  63. settingMutex.Lock()
  64. defer settingMutex.Unlock()
  65. defaultSetting = setting
  66. if defaultSetting.ConnectTimeout == 0 {
  67. defaultSetting.ConnectTimeout = 60 * time.Second
  68. }
  69. if defaultSetting.ReadWriteTimeout == 0 {
  70. defaultSetting.ReadWriteTimeout = 60 * time.Second
  71. }
  72. }
  73. // return *BeegoHttpRequest with specific method
  74. func NewBeegoRequest(rawurl, method string) *BeegoHttpRequest {
  75. var resp http.Response
  76. u, err := url.Parse(rawurl)
  77. if err != nil {
  78. log.Fatal(err)
  79. }
  80. req := http.Request{
  81. URL: u,
  82. Method: method,
  83. Header: make(http.Header),
  84. Proto: "HTTP/1.1",
  85. ProtoMajor: 1,
  86. ProtoMinor: 1,
  87. }
  88. return &BeegoHttpRequest{rawurl, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil, nil}
  89. }
  90. // Get returns *BeegoHttpRequest with GET method.
  91. func Get(url string) *BeegoHttpRequest {
  92. return NewBeegoRequest(url, "GET")
  93. }
  94. // Post returns *BeegoHttpRequest with POST method.
  95. func Post(url string) *BeegoHttpRequest {
  96. return NewBeegoRequest(url, "POST")
  97. }
  98. // Put returns *BeegoHttpRequest with PUT method.
  99. func Put(url string) *BeegoHttpRequest {
  100. return NewBeegoRequest(url, "PUT")
  101. }
  102. // Delete returns *BeegoHttpRequest DELETE method.
  103. func Delete(url string) *BeegoHttpRequest {
  104. return NewBeegoRequest(url, "DELETE")
  105. }
  106. // Head returns *BeegoHttpRequest with HEAD method.
  107. func Head(url string) *BeegoHttpRequest {
  108. return NewBeegoRequest(url, "HEAD")
  109. }
  110. // BeegoHttpSettings
  111. type BeegoHttpSettings struct {
  112. ShowDebug bool
  113. UserAgent string
  114. ConnectTimeout time.Duration
  115. ReadWriteTimeout time.Duration
  116. TlsClientConfig *tls.Config
  117. Proxy func(*http.Request) (*url.URL, error)
  118. Transport http.RoundTripper
  119. EnableCookie bool
  120. Gzip bool
  121. DumpBody bool
  122. }
  123. // BeegoHttpRequest provides more useful methods for requesting one url than http.Request.
  124. type BeegoHttpRequest struct {
  125. url string
  126. req *http.Request
  127. params map[string]string
  128. files map[string]string
  129. setting BeegoHttpSettings
  130. resp *http.Response
  131. body []byte
  132. dump []byte
  133. }
  134. // get request
  135. func (b *BeegoHttpRequest) GetRequest() *http.Request {
  136. return b.req
  137. }
  138. // Change request settings
  139. func (b *BeegoHttpRequest) Setting(setting BeegoHttpSettings) *BeegoHttpRequest {
  140. b.setting = setting
  141. return b
  142. }
  143. // SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
  144. func (b *BeegoHttpRequest) SetBasicAuth(username, password string) *BeegoHttpRequest {
  145. b.req.SetBasicAuth(username, password)
  146. return b
  147. }
  148. // SetEnableCookie sets enable/disable cookiejar
  149. func (b *BeegoHttpRequest) SetEnableCookie(enable bool) *BeegoHttpRequest {
  150. b.setting.EnableCookie = enable
  151. return b
  152. }
  153. // SetUserAgent sets User-Agent header field
  154. func (b *BeegoHttpRequest) SetUserAgent(useragent string) *BeegoHttpRequest {
  155. b.setting.UserAgent = useragent
  156. return b
  157. }
  158. // Debug sets show debug or not when executing request.
  159. func (b *BeegoHttpRequest) Debug(isdebug bool) *BeegoHttpRequest {
  160. b.setting.ShowDebug = isdebug
  161. return b
  162. }
  163. // Dump Body.
  164. func (b *BeegoHttpRequest) DumpBody(isdump bool) *BeegoHttpRequest {
  165. b.setting.DumpBody = isdump
  166. return b
  167. }
  168. // return the DumpRequest
  169. func (b *BeegoHttpRequest) DumpRequest() []byte {
  170. return b.dump
  171. }
  172. // SetTimeout sets connect time out and read-write time out for BeegoRequest.
  173. func (b *BeegoHttpRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *BeegoHttpRequest {
  174. b.setting.ConnectTimeout = connectTimeout
  175. b.setting.ReadWriteTimeout = readWriteTimeout
  176. return b
  177. }
  178. // SetTLSClientConfig sets tls connection configurations if visiting https url.
  179. func (b *BeegoHttpRequest) SetTLSClientConfig(config *tls.Config) *BeegoHttpRequest {
  180. b.setting.TlsClientConfig = config
  181. return b
  182. }
  183. // Header add header item string in request.
  184. func (b *BeegoHttpRequest) Header(key, value string) *BeegoHttpRequest {
  185. b.req.Header.Set(key, value)
  186. return b
  187. }
  188. // Set HOST
  189. func (b *BeegoHttpRequest) SetHost(host string) *BeegoHttpRequest {
  190. b.req.Host = host
  191. return b
  192. }
  193. // Set the protocol version for incoming requests.
  194. // Client requests always use HTTP/1.1.
  195. func (b *BeegoHttpRequest) SetProtocolVersion(vers string) *BeegoHttpRequest {
  196. if len(vers) == 0 {
  197. vers = "HTTP/1.1"
  198. }
  199. major, minor, ok := http.ParseHTTPVersion(vers)
  200. if ok {
  201. b.req.Proto = vers
  202. b.req.ProtoMajor = major
  203. b.req.ProtoMinor = minor
  204. }
  205. return b
  206. }
  207. // SetCookie add cookie into request.
  208. func (b *BeegoHttpRequest) SetCookie(cookie *http.Cookie) *BeegoHttpRequest {
  209. b.req.Header.Add("Cookie", cookie.String())
  210. return b
  211. }
  212. // Set transport to
  213. func (b *BeegoHttpRequest) SetTransport(transport http.RoundTripper) *BeegoHttpRequest {
  214. b.setting.Transport = transport
  215. return b
  216. }
  217. // Set http proxy
  218. // example:
  219. //
  220. // func(req *http.Request) (*url.URL, error) {
  221. // u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
  222. // return u, nil
  223. // }
  224. func (b *BeegoHttpRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHttpRequest {
  225. b.setting.Proxy = proxy
  226. return b
  227. }
  228. // Param adds query param in to request.
  229. // params build query string as ?key1=value1&key2=value2...
  230. func (b *BeegoHttpRequest) Param(key, value string) *BeegoHttpRequest {
  231. b.params[key] = value
  232. return b
  233. }
  234. func (b *BeegoHttpRequest) PostFile(formname, filename string) *BeegoHttpRequest {
  235. b.files[formname] = filename
  236. return b
  237. }
  238. // Body adds request raw body.
  239. // it supports string and []byte.
  240. func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest {
  241. switch t := data.(type) {
  242. case string:
  243. bf := bytes.NewBufferString(t)
  244. b.req.Body = ioutil.NopCloser(bf)
  245. b.req.ContentLength = int64(len(t))
  246. case []byte:
  247. bf := bytes.NewBuffer(t)
  248. b.req.Body = ioutil.NopCloser(bf)
  249. b.req.ContentLength = int64(len(t))
  250. }
  251. return b
  252. }
  253. // JsonBody adds request raw body encoding by JSON.
  254. func (b *BeegoHttpRequest) JsonBody(obj interface{}) (*BeegoHttpRequest, error) {
  255. if b.req.Body == nil && obj != nil {
  256. buf := bytes.NewBuffer(nil)
  257. enc := json.NewEncoder(buf)
  258. if err := enc.Encode(obj); err != nil {
  259. return b, err
  260. }
  261. b.req.Body = ioutil.NopCloser(buf)
  262. b.req.ContentLength = int64(buf.Len())
  263. b.req.Header.Set("Content-Type", "application/json")
  264. }
  265. return b, nil
  266. }
  267. func (b *BeegoHttpRequest) buildUrl(paramBody string) {
  268. // build GET url with query string
  269. if b.req.Method == "GET" && len(paramBody) > 0 {
  270. if strings.Index(b.url, "?") != -1 {
  271. b.url += "&" + paramBody
  272. } else {
  273. b.url = b.url + "?" + paramBody
  274. }
  275. return
  276. }
  277. // build POST/PUT/PATCH url and body
  278. if (b.req.Method == "POST" || b.req.Method == "PUT" || b.req.Method == "PATCH") && b.req.Body == nil {
  279. // with files
  280. if len(b.files) > 0 {
  281. pr, pw := io.Pipe()
  282. bodyWriter := multipart.NewWriter(pw)
  283. go func() {
  284. for formname, filename := range b.files {
  285. fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
  286. if err != nil {
  287. log.Fatal(err)
  288. }
  289. fh, err := os.Open(filename)
  290. if err != nil {
  291. log.Fatal(err)
  292. }
  293. //iocopy
  294. _, err = io.Copy(fileWriter, fh)
  295. fh.Close()
  296. if err != nil {
  297. log.Fatal(err)
  298. }
  299. }
  300. for k, v := range b.params {
  301. bodyWriter.WriteField(k, v)
  302. }
  303. bodyWriter.Close()
  304. pw.Close()
  305. }()
  306. b.Header("Content-Type", bodyWriter.FormDataContentType())
  307. b.req.Body = ioutil.NopCloser(pr)
  308. return
  309. }
  310. // with params
  311. if len(paramBody) > 0 {
  312. b.Header("Content-Type", "application/x-www-form-urlencoded")
  313. b.Body(paramBody)
  314. }
  315. }
  316. }
  317. func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
  318. if b.resp.StatusCode != 0 {
  319. return b.resp, nil
  320. }
  321. resp, err := b.SendOut()
  322. if err != nil {
  323. return nil, err
  324. }
  325. b.resp = resp
  326. return resp, nil
  327. }
  328. func (b *BeegoHttpRequest) SendOut() (*http.Response, error) {
  329. var paramBody string
  330. if len(b.params) > 0 {
  331. var buf bytes.Buffer
  332. for k, v := range b.params {
  333. buf.WriteString(url.QueryEscape(k))
  334. buf.WriteByte('=')
  335. buf.WriteString(url.QueryEscape(v))
  336. buf.WriteByte('&')
  337. }
  338. paramBody = buf.String()
  339. paramBody = paramBody[0 : len(paramBody)-1]
  340. }
  341. b.buildUrl(paramBody)
  342. url, err := url.Parse(b.url)
  343. if err != nil {
  344. return nil, err
  345. }
  346. b.req.URL = url
  347. trans := b.setting.Transport
  348. if trans == nil {
  349. // create default transport
  350. trans = &http.Transport{
  351. TLSClientConfig: b.setting.TlsClientConfig,
  352. Proxy: b.setting.Proxy,
  353. Dial: TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout),
  354. }
  355. } else {
  356. // if b.transport is *http.Transport then set the settings.
  357. if t, ok := trans.(*http.Transport); ok {
  358. if t.TLSClientConfig == nil {
  359. t.TLSClientConfig = b.setting.TlsClientConfig
  360. }
  361. if t.Proxy == nil {
  362. t.Proxy = b.setting.Proxy
  363. }
  364. if t.Dial == nil {
  365. t.Dial = TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout)
  366. }
  367. }
  368. }
  369. var jar http.CookieJar = nil
  370. if b.setting.EnableCookie {
  371. if defaultCookieJar == nil {
  372. createDefaultCookie()
  373. }
  374. jar = defaultCookieJar
  375. }
  376. client := &http.Client{
  377. Transport: trans,
  378. Jar: jar,
  379. }
  380. if b.setting.UserAgent != "" && b.req.Header.Get("User-Agent") == "" {
  381. b.req.Header.Set("User-Agent", b.setting.UserAgent)
  382. }
  383. if b.setting.ShowDebug {
  384. dump, err := httputil.DumpRequest(b.req, b.setting.DumpBody)
  385. if err != nil {
  386. println(err.Error())
  387. }
  388. b.dump = dump
  389. }
  390. return client.Do(b.req)
  391. }
  392. // String returns the body string in response.
  393. // it calls Response inner.
  394. func (b *BeegoHttpRequest) String() (string, error) {
  395. data, err := b.Bytes()
  396. if err != nil {
  397. return "", err
  398. }
  399. return string(data), nil
  400. }
  401. // Bytes returns the body []byte in response.
  402. // it calls Response inner.
  403. func (b *BeegoHttpRequest) Bytes() ([]byte, error) {
  404. if b.body != nil {
  405. return b.body, nil
  406. }
  407. resp, err := b.getResponse()
  408. if err != nil {
  409. return nil, err
  410. }
  411. if resp.Body == nil {
  412. return nil, nil
  413. }
  414. defer resp.Body.Close()
  415. if b.setting.Gzip && resp.Header.Get("Content-Encoding") == "gzip" {
  416. reader, err := gzip.NewReader(resp.Body)
  417. if err != nil {
  418. return nil, err
  419. }
  420. b.body, err = ioutil.ReadAll(reader)
  421. } else {
  422. b.body, err = ioutil.ReadAll(resp.Body)
  423. }
  424. if err != nil {
  425. return nil, err
  426. }
  427. return b.body, nil
  428. }
  429. // ToFile saves the body data in response to one file.
  430. // it calls Response inner.
  431. func (b *BeegoHttpRequest) ToFile(filename string) error {
  432. f, err := os.Create(filename)
  433. if err != nil {
  434. return err
  435. }
  436. defer f.Close()
  437. resp, err := b.getResponse()
  438. if err != nil {
  439. return err
  440. }
  441. if resp.Body == nil {
  442. return nil
  443. }
  444. defer resp.Body.Close()
  445. _, err = io.Copy(f, resp.Body)
  446. return err
  447. }
  448. // ToJson returns the map that marshals from the body bytes as json in response .
  449. // it calls Response inner.
  450. func (b *BeegoHttpRequest) ToJson(v interface{}) error {
  451. data, err := b.Bytes()
  452. if err != nil {
  453. return err
  454. }
  455. return json.Unmarshal(data, v)
  456. }
  457. // ToXml returns the map that marshals from the body bytes as xml in response .
  458. // it calls Response inner.
  459. func (b *BeegoHttpRequest) ToXml(v interface{}) error {
  460. data, err := b.Bytes()
  461. if err != nil {
  462. return err
  463. }
  464. return xml.Unmarshal(data, v)
  465. }
  466. // Response executes request client gets response mannually.
  467. func (b *BeegoHttpRequest) Response() (*http.Response, error) {
  468. return b.getResponse()
  469. }
  470. // TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.
  471. func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
  472. return func(netw, addr string) (net.Conn, error) {
  473. conn, err := net.DialTimeout(netw, addr, cTimeout)
  474. if err != nil {
  475. return nil, err
  476. }
  477. conn.SetDeadline(time.Now().Add(rwTimeout))
  478. return conn, nil
  479. }
  480. }