httplib.go 15 KB

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