httplib.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. // Copyright 2014 beego Author. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package httplib is used as http.Client
  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. "gopkg.in/yaml.v2"
  39. "io"
  40. "io/ioutil"
  41. "log"
  42. "mime/multipart"
  43. "net"
  44. "net/http"
  45. "net/http/cookiejar"
  46. "net/http/httputil"
  47. "net/url"
  48. "os"
  49. "strings"
  50. "sync"
  51. "time"
  52. )
  53. var defaultSetting = BeegoHTTPSettings{
  54. UserAgent: "beegoServer",
  55. ConnectTimeout: 60 * time.Second,
  56. ReadWriteTimeout: 60 * time.Second,
  57. Gzip: true,
  58. DumpBody: true,
  59. }
  60. var defaultCookieJar http.CookieJar
  61. var settingMutex sync.Mutex
  62. // createDefaultCookie creates a global cookiejar to store cookies.
  63. func createDefaultCookie() {
  64. settingMutex.Lock()
  65. defer settingMutex.Unlock()
  66. defaultCookieJar, _ = cookiejar.New(nil)
  67. }
  68. // SetDefaultSetting Overwrite default settings
  69. func SetDefaultSetting(setting BeegoHTTPSettings) {
  70. settingMutex.Lock()
  71. defer settingMutex.Unlock()
  72. defaultSetting = setting
  73. }
  74. // NewBeegoRequest return *BeegoHttpRequest with specific method
  75. func NewBeegoRequest(rawurl, method string) *BeegoHTTPRequest {
  76. var resp http.Response
  77. u, err := url.Parse(rawurl)
  78. if err != nil {
  79. log.Println("Httplib:", err)
  80. }
  81. req := http.Request{
  82. URL: u,
  83. Method: method,
  84. Header: make(http.Header),
  85. Proto: "HTTP/1.1",
  86. ProtoMajor: 1,
  87. ProtoMinor: 1,
  88. }
  89. return &BeegoHTTPRequest{
  90. url: rawurl,
  91. req: &req,
  92. params: map[string][]string{},
  93. files: map[string]string{},
  94. setting: defaultSetting,
  95. resp: &resp,
  96. }
  97. }
  98. // Get returns *BeegoHttpRequest with GET method.
  99. func Get(url string) *BeegoHTTPRequest {
  100. return NewBeegoRequest(url, "GET")
  101. }
  102. // Post returns *BeegoHttpRequest with POST method.
  103. func Post(url string) *BeegoHTTPRequest {
  104. return NewBeegoRequest(url, "POST")
  105. }
  106. // Put returns *BeegoHttpRequest with PUT method.
  107. func Put(url string) *BeegoHTTPRequest {
  108. return NewBeegoRequest(url, "PUT")
  109. }
  110. // Delete returns *BeegoHttpRequest DELETE method.
  111. func Delete(url string) *BeegoHTTPRequest {
  112. return NewBeegoRequest(url, "DELETE")
  113. }
  114. // Head returns *BeegoHttpRequest with HEAD method.
  115. func Head(url string) *BeegoHTTPRequest {
  116. return NewBeegoRequest(url, "HEAD")
  117. }
  118. // BeegoHTTPSettings is the http.Client setting
  119. type BeegoHTTPSettings struct {
  120. ShowDebug bool
  121. UserAgent string
  122. ConnectTimeout time.Duration
  123. ReadWriteTimeout time.Duration
  124. TLSClientConfig *tls.Config
  125. Proxy func(*http.Request) (*url.URL, error)
  126. Transport http.RoundTripper
  127. CheckRedirect func(req *http.Request, via []*http.Request) error
  128. EnableCookie bool
  129. Gzip bool
  130. DumpBody bool
  131. Retries int // if set to -1 means will retry forever
  132. }
  133. // BeegoHTTPRequest provides more useful methods for requesting one url than http.Request.
  134. type BeegoHTTPRequest struct {
  135. url string
  136. req *http.Request
  137. params map[string][]string
  138. files map[string]string
  139. setting BeegoHTTPSettings
  140. resp *http.Response
  141. body []byte
  142. dump []byte
  143. }
  144. // GetRequest return the request object
  145. func (b *BeegoHTTPRequest) GetRequest() *http.Request {
  146. return b.req
  147. }
  148. // Setting Change request settings
  149. func (b *BeegoHTTPRequest) Setting(setting BeegoHTTPSettings) *BeegoHTTPRequest {
  150. b.setting = setting
  151. return b
  152. }
  153. // SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
  154. func (b *BeegoHTTPRequest) SetBasicAuth(username, password string) *BeegoHTTPRequest {
  155. b.req.SetBasicAuth(username, password)
  156. return b
  157. }
  158. // SetEnableCookie sets enable/disable cookiejar
  159. func (b *BeegoHTTPRequest) SetEnableCookie(enable bool) *BeegoHTTPRequest {
  160. b.setting.EnableCookie = enable
  161. return b
  162. }
  163. // SetUserAgent sets User-Agent header field
  164. func (b *BeegoHTTPRequest) SetUserAgent(useragent string) *BeegoHTTPRequest {
  165. b.setting.UserAgent = useragent
  166. return b
  167. }
  168. // Debug sets show debug or not when executing request.
  169. func (b *BeegoHTTPRequest) Debug(isdebug bool) *BeegoHTTPRequest {
  170. b.setting.ShowDebug = isdebug
  171. return b
  172. }
  173. // Retries sets Retries times.
  174. // default is 0 means no retried.
  175. // -1 means retried forever.
  176. // others means retried times.
  177. func (b *BeegoHTTPRequest) Retries(times int) *BeegoHTTPRequest {
  178. b.setting.Retries = times
  179. return b
  180. }
  181. // DumpBody setting whether need to Dump the Body.
  182. func (b *BeegoHTTPRequest) DumpBody(isdump bool) *BeegoHTTPRequest {
  183. b.setting.DumpBody = isdump
  184. return b
  185. }
  186. // DumpRequest return the DumpRequest
  187. func (b *BeegoHTTPRequest) DumpRequest() []byte {
  188. return b.dump
  189. }
  190. // SetTimeout sets connect time out and read-write time out for BeegoRequest.
  191. func (b *BeegoHTTPRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *BeegoHTTPRequest {
  192. b.setting.ConnectTimeout = connectTimeout
  193. b.setting.ReadWriteTimeout = readWriteTimeout
  194. return b
  195. }
  196. // SetTLSClientConfig sets tls connection configurations if visiting https url.
  197. func (b *BeegoHTTPRequest) SetTLSClientConfig(config *tls.Config) *BeegoHTTPRequest {
  198. b.setting.TLSClientConfig = config
  199. return b
  200. }
  201. // Header add header item string in request.
  202. func (b *BeegoHTTPRequest) Header(key, value string) *BeegoHTTPRequest {
  203. b.req.Header.Set(key, value)
  204. return b
  205. }
  206. // SetHost set the request host
  207. func (b *BeegoHTTPRequest) SetHost(host string) *BeegoHTTPRequest {
  208. b.req.Host = host
  209. return b
  210. }
  211. // SetProtocolVersion Set the protocol version for incoming requests.
  212. // Client requests always use HTTP/1.1.
  213. func (b *BeegoHTTPRequest) SetProtocolVersion(vers string) *BeegoHTTPRequest {
  214. if len(vers) == 0 {
  215. vers = "HTTP/1.1"
  216. }
  217. major, minor, ok := http.ParseHTTPVersion(vers)
  218. if ok {
  219. b.req.Proto = vers
  220. b.req.ProtoMajor = major
  221. b.req.ProtoMinor = minor
  222. }
  223. return b
  224. }
  225. // SetCookie add cookie into request.
  226. func (b *BeegoHTTPRequest) SetCookie(cookie *http.Cookie) *BeegoHTTPRequest {
  227. b.req.Header.Add("Cookie", cookie.String())
  228. return b
  229. }
  230. // SetTransport set the setting transport
  231. func (b *BeegoHTTPRequest) SetTransport(transport http.RoundTripper) *BeegoHTTPRequest {
  232. b.setting.Transport = transport
  233. return b
  234. }
  235. // SetProxy set the http proxy
  236. // example:
  237. //
  238. // func(req *http.Request) (*url.URL, error) {
  239. // u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
  240. // return u, nil
  241. // }
  242. func (b *BeegoHTTPRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHTTPRequest {
  243. b.setting.Proxy = proxy
  244. return b
  245. }
  246. // SetCheckRedirect specifies the policy for handling redirects.
  247. //
  248. // If CheckRedirect is nil, the Client uses its default policy,
  249. // which is to stop after 10 consecutive requests.
  250. func (b *BeegoHTTPRequest) SetCheckRedirect(redirect func(req *http.Request, via []*http.Request) error) *BeegoHTTPRequest {
  251. b.setting.CheckRedirect = redirect
  252. return b
  253. }
  254. // Param adds query param in to request.
  255. // params build query string as ?key1=value1&key2=value2...
  256. func (b *BeegoHTTPRequest) Param(key, value string) *BeegoHTTPRequest {
  257. if param, ok := b.params[key]; ok {
  258. b.params[key] = append(param, value)
  259. } else {
  260. b.params[key] = []string{value}
  261. }
  262. return b
  263. }
  264. // PostFile add a post file to the request
  265. func (b *BeegoHTTPRequest) PostFile(formname, filename string) *BeegoHTTPRequest {
  266. b.files[formname] = filename
  267. return b
  268. }
  269. // Body adds request raw body.
  270. // it supports string and []byte.
  271. func (b *BeegoHTTPRequest) Body(data interface{}) *BeegoHTTPRequest {
  272. switch t := data.(type) {
  273. case string:
  274. bf := bytes.NewBufferString(t)
  275. b.req.Body = ioutil.NopCloser(bf)
  276. b.req.ContentLength = int64(len(t))
  277. case []byte:
  278. bf := bytes.NewBuffer(t)
  279. b.req.Body = ioutil.NopCloser(bf)
  280. b.req.ContentLength = int64(len(t))
  281. }
  282. return b
  283. }
  284. // XMLBody adds request raw body encoding by XML.
  285. func (b *BeegoHTTPRequest) XMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
  286. if b.req.Body == nil && obj != nil {
  287. byts, err := xml.Marshal(obj)
  288. if err != nil {
  289. return b, err
  290. }
  291. b.req.Body = ioutil.NopCloser(bytes.NewReader(byts))
  292. b.req.ContentLength = int64(len(byts))
  293. b.req.Header.Set("Content-Type", "application/xml")
  294. }
  295. return b, nil
  296. }
  297. // YAMLBody adds request raw body encoding by YAML.
  298. func (b *BeegoHTTPRequest) YAMLBody(obj interface{}) (*BeegoHTTPRequest, error) {
  299. if b.req.Body == nil && obj != nil {
  300. byts, err := yaml.Marshal(obj)
  301. if err != nil {
  302. return b, err
  303. }
  304. b.req.Body = ioutil.NopCloser(bytes.NewReader(byts))
  305. b.req.ContentLength = int64(len(byts))
  306. b.req.Header.Set("Content-Type", "application/x+yaml")
  307. }
  308. return b, nil
  309. }
  310. // JSONBody adds request raw body encoding by JSON.
  311. func (b *BeegoHTTPRequest) JSONBody(obj interface{}) (*BeegoHTTPRequest, error) {
  312. if b.req.Body == nil && obj != nil {
  313. byts, err := json.Marshal(obj)
  314. if err != nil {
  315. return b, err
  316. }
  317. b.req.Body = ioutil.NopCloser(bytes.NewReader(byts))
  318. b.req.ContentLength = int64(len(byts))
  319. b.req.Header.Set("Content-Type", "application/json")
  320. }
  321. return b, nil
  322. }
  323. func (b *BeegoHTTPRequest) buildURL(paramBody string) {
  324. // build GET url with query string
  325. if b.req.Method == "GET" && len(paramBody) > 0 {
  326. if strings.Contains(b.url, "?") {
  327. b.url += "&" + paramBody
  328. } else {
  329. b.url = b.url + "?" + paramBody
  330. }
  331. return
  332. }
  333. // build POST/PUT/PATCH url and body
  334. if (b.req.Method == "POST" || b.req.Method == "PUT" || b.req.Method == "PATCH" || b.req.Method == "DELETE") && b.req.Body == nil {
  335. // with files
  336. if len(b.files) > 0 {
  337. pr, pw := io.Pipe()
  338. bodyWriter := multipart.NewWriter(pw)
  339. go func() {
  340. for formname, filename := range b.files {
  341. fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
  342. if err != nil {
  343. log.Println("Httplib:", err)
  344. }
  345. fh, err := os.Open(filename)
  346. if err != nil {
  347. log.Println("Httplib:", err)
  348. }
  349. //iocopy
  350. _, err = io.Copy(fileWriter, fh)
  351. fh.Close()
  352. if err != nil {
  353. log.Println("Httplib:", err)
  354. }
  355. }
  356. for k, v := range b.params {
  357. for _, vv := range v {
  358. bodyWriter.WriteField(k, vv)
  359. }
  360. }
  361. bodyWriter.Close()
  362. pw.Close()
  363. }()
  364. b.Header("Content-Type", bodyWriter.FormDataContentType())
  365. b.req.Body = ioutil.NopCloser(pr)
  366. return
  367. }
  368. // with params
  369. if len(paramBody) > 0 {
  370. b.Header("Content-Type", "application/x-www-form-urlencoded")
  371. b.Body(paramBody)
  372. }
  373. }
  374. }
  375. func (b *BeegoHTTPRequest) getResponse() (*http.Response, error) {
  376. if b.resp.StatusCode != 0 {
  377. return b.resp, nil
  378. }
  379. resp, err := b.DoRequest()
  380. if err != nil {
  381. return nil, err
  382. }
  383. b.resp = resp
  384. return resp, nil
  385. }
  386. // DoRequest will do the client.Do
  387. func (b *BeegoHTTPRequest) DoRequest() (resp *http.Response, err error) {
  388. var paramBody string
  389. if len(b.params) > 0 {
  390. var buf bytes.Buffer
  391. for k, v := range b.params {
  392. for _, vv := range v {
  393. buf.WriteString(url.QueryEscape(k))
  394. buf.WriteByte('=')
  395. buf.WriteString(url.QueryEscape(vv))
  396. buf.WriteByte('&')
  397. }
  398. }
  399. paramBody = buf.String()
  400. paramBody = paramBody[0 : len(paramBody)-1]
  401. }
  402. b.buildURL(paramBody)
  403. urlParsed, err := url.Parse(b.url)
  404. if err != nil {
  405. return nil, err
  406. }
  407. b.req.URL = urlParsed
  408. trans := b.setting.Transport
  409. if trans == nil {
  410. // create default transport
  411. trans = &http.Transport{
  412. TLSClientConfig: b.setting.TLSClientConfig,
  413. Proxy: b.setting.Proxy,
  414. Dial: TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout),
  415. MaxIdleConnsPerHost: 100,
  416. }
  417. } else {
  418. // if b.transport is *http.Transport then set the settings.
  419. if t, ok := trans.(*http.Transport); ok {
  420. if t.TLSClientConfig == nil {
  421. t.TLSClientConfig = b.setting.TLSClientConfig
  422. }
  423. if t.Proxy == nil {
  424. t.Proxy = b.setting.Proxy
  425. }
  426. if t.Dial == nil {
  427. t.Dial = TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout)
  428. }
  429. }
  430. }
  431. var jar http.CookieJar
  432. if b.setting.EnableCookie {
  433. if defaultCookieJar == nil {
  434. createDefaultCookie()
  435. }
  436. jar = defaultCookieJar
  437. }
  438. client := &http.Client{
  439. Transport: trans,
  440. Jar: jar,
  441. }
  442. if b.setting.UserAgent != "" && b.req.Header.Get("User-Agent") == "" {
  443. b.req.Header.Set("User-Agent", b.setting.UserAgent)
  444. }
  445. if b.setting.CheckRedirect != nil {
  446. client.CheckRedirect = b.setting.CheckRedirect
  447. }
  448. if b.setting.ShowDebug {
  449. dump, err := httputil.DumpRequest(b.req, b.setting.DumpBody)
  450. if err != nil {
  451. log.Println(err.Error())
  452. }
  453. b.dump = dump
  454. }
  455. // retries default value is 0, it will run once.
  456. // retries equal to -1, it will run forever until success
  457. // retries is setted, it will retries fixed times.
  458. for i := 0; b.setting.Retries == -1 || i <= b.setting.Retries; i++ {
  459. resp, err = client.Do(b.req)
  460. if err == nil {
  461. break
  462. }
  463. }
  464. return resp, err
  465. }
  466. // String returns the body string in response.
  467. // it calls Response inner.
  468. func (b *BeegoHTTPRequest) String() (string, error) {
  469. data, err := b.Bytes()
  470. if err != nil {
  471. return "", err
  472. }
  473. return string(data), nil
  474. }
  475. // Bytes returns the body []byte in response.
  476. // it calls Response inner.
  477. func (b *BeegoHTTPRequest) Bytes() ([]byte, error) {
  478. if b.body != nil {
  479. return b.body, nil
  480. }
  481. resp, err := b.getResponse()
  482. if err != nil {
  483. return nil, err
  484. }
  485. if resp.Body == nil {
  486. return nil, nil
  487. }
  488. defer resp.Body.Close()
  489. if b.setting.Gzip && resp.Header.Get("Content-Encoding") == "gzip" {
  490. reader, err := gzip.NewReader(resp.Body)
  491. if err != nil {
  492. return nil, err
  493. }
  494. b.body, err = ioutil.ReadAll(reader)
  495. return b.body, err
  496. }
  497. b.body, err = ioutil.ReadAll(resp.Body)
  498. return b.body, err
  499. }
  500. // ToFile saves the body data in response to one file.
  501. // it calls Response inner.
  502. func (b *BeegoHTTPRequest) ToFile(filename string) error {
  503. f, err := os.Create(filename)
  504. if err != nil {
  505. return err
  506. }
  507. defer f.Close()
  508. resp, err := b.getResponse()
  509. if err != nil {
  510. return err
  511. }
  512. if resp.Body == nil {
  513. return nil
  514. }
  515. defer resp.Body.Close()
  516. _, err = io.Copy(f, resp.Body)
  517. return err
  518. }
  519. // ToJSON returns the map that marshals from the body bytes as json in response .
  520. // it calls Response inner.
  521. func (b *BeegoHTTPRequest) ToJSON(v interface{}) error {
  522. data, err := b.Bytes()
  523. if err != nil {
  524. return err
  525. }
  526. return json.Unmarshal(data, v)
  527. }
  528. // ToXML returns the map that marshals from the body bytes as xml in response .
  529. // it calls Response inner.
  530. func (b *BeegoHTTPRequest) ToXML(v interface{}) error {
  531. data, err := b.Bytes()
  532. if err != nil {
  533. return err
  534. }
  535. return xml.Unmarshal(data, v)
  536. }
  537. // ToYAML returns the map that marshals from the body bytes as yaml in response .
  538. // it calls Response inner.
  539. func (b *BeegoHTTPRequest) ToYAML(v interface{}) error {
  540. data, err := b.Bytes()
  541. if err != nil {
  542. return err
  543. }
  544. return yaml.Unmarshal(data, v)
  545. }
  546. // Response executes request client gets response mannually.
  547. func (b *BeegoHTTPRequest) Response() (*http.Response, error) {
  548. return b.getResponse()
  549. }
  550. // TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.
  551. func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(net, addr string) (c net.Conn, err error) {
  552. return func(netw, addr string) (net.Conn, error) {
  553. conn, err := net.DialTimeout(netw, addr, cTimeout)
  554. if err != nil {
  555. return nil, err
  556. }
  557. err = conn.SetDeadline(time.Now().Add(rwTimeout))
  558. return conn, err
  559. }
  560. }