httplib.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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. // copy & modify from github.com/astaxie/beego/tree/master/httplib
  15. package httplib
  16. import (
  17. "bytes"
  18. "compress/gzip"
  19. "crypto/tls"
  20. "encoding/json"
  21. "encoding/xml"
  22. "io"
  23. "io/ioutil"
  24. "log"
  25. "mime/multipart"
  26. "net"
  27. "net/http"
  28. "net/http/cookiejar"
  29. "net/http/httputil"
  30. "net/url"
  31. "os"
  32. "strings"
  33. "sync"
  34. "time"
  35. )
  36. var defaultSetting = HTTPSettings{
  37. //UserAgent: "smart-push",
  38. Gzip: true,
  39. DumpBody: true,
  40. ConnectTimeout: time.Second * 30,
  41. KeepAlive: time.Second * 60,
  42. Transport: &http.Transport{
  43. DialContext: (&net.Dialer{
  44. Timeout: time.Second * 30,
  45. KeepAlive: time.Second * 60,
  46. }).DialContext,
  47. MaxIdleConnsPerHost: 3000,
  48. MaxIdleConns: 30000,
  49. },
  50. }
  51. var defaultCookieJar http.CookieJar
  52. var settingMutex sync.Mutex
  53. // createDefaultCookie creates a global cookiejar to store cookies.
  54. func createDefaultCookie() {
  55. settingMutex.Lock()
  56. defer settingMutex.Unlock()
  57. defaultCookieJar, _ = cookiejar.New(nil)
  58. }
  59. // SetDefaultSetting Overwrite default settings
  60. func SetDefaultSetting(setting HTTPSettings) {
  61. settingMutex.Lock()
  62. defer settingMutex.Unlock()
  63. defaultSetting = setting
  64. }
  65. // NewBeegoRequest return *HTTPRequest with specific method
  66. func NewHTTPRequest(rawurl, method string) *HTTPRequest {
  67. var resp http.Response
  68. u, err := url.Parse(rawurl)
  69. if err != nil {
  70. log.Println("Httplib:", err)
  71. }
  72. req := http.Request{
  73. URL: u,
  74. Method: method,
  75. Header: make(http.Header),
  76. Proto: "HTTP/1.1",
  77. ProtoMajor: 1,
  78. ProtoMinor: 1,
  79. }
  80. return &HTTPRequest{
  81. url: rawurl,
  82. req: &req,
  83. params: map[string][]string{},
  84. files: map[string]string{},
  85. setting: defaultSetting,
  86. resp: &resp,
  87. }
  88. }
  89. // Get returns *HTTPRequest with GET method.
  90. func Get(url string) *HTTPRequest {
  91. return NewHTTPRequest(url, "GET")
  92. }
  93. // Post returns *HTTPRequest with POST method.
  94. func Post(url string) *HTTPRequest {
  95. return NewHTTPRequest(url, "POST")
  96. }
  97. // Put returns *HTTPRequest with PUT method.
  98. func Put(url string) *HTTPRequest {
  99. return NewHTTPRequest(url, "PUT")
  100. }
  101. // Delete returns *HTTPRequest DELETE method.
  102. func Delete(url string) *HTTPRequest {
  103. return NewHTTPRequest(url, "DELETE")
  104. }
  105. // Head returns *HTTPRequest with HEAD method.
  106. func Head(url string) *HTTPRequest {
  107. return NewHTTPRequest(url, "HEAD")
  108. }
  109. // HTTPSettings is the http.Client setting
  110. type HTTPSettings struct {
  111. ShowDebug bool
  112. UserAgent string
  113. TLSClientConfig *tls.Config
  114. Proxy func(*http.Request) (*url.URL, error)
  115. Transport http.RoundTripper
  116. CheckRedirect func(req *http.Request, via []*http.Request) error
  117. EnableCookie bool
  118. Gzip bool
  119. DumpBody bool
  120. Retries int // if set to -1 means will retry forever
  121. ConnectTimeout time.Duration
  122. KeepAlive time.Duration
  123. Timeout time.Duration
  124. }
  125. // HTTPRequest provides more useful methods for requesting one url than http.Request.
  126. type HTTPRequest struct {
  127. url string
  128. req *http.Request
  129. params map[string][]string
  130. files map[string]string
  131. setting HTTPSettings
  132. resp *http.Response
  133. body []byte
  134. dump []byte
  135. client *http.Client
  136. }
  137. // GetRequest return the request object
  138. func (b *HTTPRequest) GetRequest() *http.Request {
  139. return b.req
  140. }
  141. // Setting Change request settings
  142. func (b *HTTPRequest) Setting(setting HTTPSettings) *HTTPRequest {
  143. b.setting = setting
  144. return b
  145. }
  146. // SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
  147. func (b *HTTPRequest) SetBasicAuth(username, password string) *HTTPRequest {
  148. b.req.SetBasicAuth(username, password)
  149. return b
  150. }
  151. // SetEnableCookie sets enable/disable cookiejar
  152. func (b *HTTPRequest) SetEnableCookie(enable bool) *HTTPRequest {
  153. b.setting.EnableCookie = enable
  154. return b
  155. }
  156. // SetUserAgent sets User-Agent header field
  157. func (b *HTTPRequest) SetUserAgent(useragent string) *HTTPRequest {
  158. b.setting.UserAgent = useragent
  159. return b
  160. }
  161. // Debug sets show debug or not when executing request.
  162. func (b *HTTPRequest) Debug(isdebug bool) *HTTPRequest {
  163. b.setting.ShowDebug = isdebug
  164. return b
  165. }
  166. // Retries sets Retries times.
  167. // default is 0 means no retried.
  168. // -1 means retried forever.
  169. // others means retried times.
  170. func (b *HTTPRequest) Retries(times int) *HTTPRequest {
  171. b.setting.Retries = times
  172. return b
  173. }
  174. // DumpBody setting whether need to Dump the Body.
  175. func (b *HTTPRequest) DumpBody(isdump bool) *HTTPRequest {
  176. b.setting.DumpBody = isdump
  177. return b
  178. }
  179. // DumpRequest return the DumpRequest
  180. func (b *HTTPRequest) DumpRequest() []byte {
  181. return b.dump
  182. }
  183. // SetTimeout sets connect time out and read-write time out for BeegoRequest.
  184. func (b *HTTPRequest) SetTimeout(timeout time.Duration) *HTTPRequest {
  185. b.setting.Timeout = timeout
  186. return b
  187. }
  188. // SetTLSClientConfig sets tls connection configurations if visiting https url.
  189. func (b *HTTPRequest) SetTLSClientConfig(config *tls.Config) *HTTPRequest {
  190. b.setting.TLSClientConfig = config
  191. return b
  192. }
  193. // Header add header item string in request.
  194. func (b *HTTPRequest) Header(key, value string) *HTTPRequest {
  195. b.req.Header.Set(key, value)
  196. return b
  197. }
  198. // SetHost set the request host
  199. func (b *HTTPRequest) SetHost(host string) *HTTPRequest {
  200. b.req.Host = host
  201. return b
  202. }
  203. // SetProtocolVersion Set the protocol version for incoming requests.
  204. // Client requests always use HTTP/1.1.
  205. func (b *HTTPRequest) SetProtocolVersion(vers string) *HTTPRequest {
  206. if len(vers) == 0 {
  207. vers = "HTTP/1.1"
  208. }
  209. major, minor, ok := http.ParseHTTPVersion(vers)
  210. if ok {
  211. b.req.Proto = vers
  212. b.req.ProtoMajor = major
  213. b.req.ProtoMinor = minor
  214. }
  215. return b
  216. }
  217. // SetCookie add cookie into request.
  218. func (b *HTTPRequest) SetCookie(cookie *http.Cookie) *HTTPRequest {
  219. b.req.Header.Add("Cookie", cookie.String())
  220. return b
  221. }
  222. // SetTransport set the setting transport
  223. func (b *HTTPRequest) SetTransport(transport http.RoundTripper) *HTTPRequest {
  224. b.setting.Transport = transport
  225. return b
  226. }
  227. // SetProxy set the http proxy
  228. // example:
  229. //
  230. // func(req *http.Request) (*url.URL, error) {
  231. // u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
  232. // return u, nil
  233. // }
  234. func (b *HTTPRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *HTTPRequest {
  235. b.setting.Proxy = proxy
  236. return b
  237. }
  238. // SetCheckRedirect specifies the policy for handling redirects.
  239. //
  240. // If CheckRedirect is nil, the Client uses its default policy,
  241. // which is to stop after 10 consecutive requests.
  242. func (b *HTTPRequest) SetCheckRedirect(redirect func(req *http.Request, via []*http.Request) error) *HTTPRequest {
  243. b.setting.CheckRedirect = redirect
  244. return b
  245. }
  246. // Param adds query param in to request.
  247. // params build query string as ?key1=value1&key2=value2...
  248. func (b *HTTPRequest) Param(key, value string) *HTTPRequest {
  249. if param, ok := b.params[key]; ok {
  250. b.params[key] = append(param, value)
  251. } else {
  252. b.params[key] = []string{value}
  253. }
  254. return b
  255. }
  256. // PostFile add a post file to the request
  257. func (b *HTTPRequest) PostFile(formname, filename string) *HTTPRequest {
  258. b.files[formname] = filename
  259. return b
  260. }
  261. // Body adds request raw body.
  262. // it supports string and []byte.
  263. func (b *HTTPRequest) Body(data interface{}) *HTTPRequest {
  264. switch t := data.(type) {
  265. case string:
  266. bf := bytes.NewBufferString(t)
  267. b.req.Body = ioutil.NopCloser(bf)
  268. b.req.ContentLength = int64(len(t))
  269. case []byte:
  270. bf := bytes.NewBuffer(t)
  271. b.req.Body = ioutil.NopCloser(bf)
  272. b.req.ContentLength = int64(len(t))
  273. }
  274. return b
  275. }
  276. // JSONBody adds request raw body encoding by JSON.
  277. func (b *HTTPRequest) JSONBody(obj interface{}) (*HTTPRequest, error) {
  278. if b.req.Body == nil && obj != nil {
  279. byts, err := json.Marshal(obj)
  280. if err != nil {
  281. return b, err
  282. }
  283. b.req.Body = ioutil.NopCloser(bytes.NewReader(byts))
  284. b.req.ContentLength = int64(len(byts))
  285. b.req.Header.Set("Content-Type", "application/json")
  286. }
  287. return b, nil
  288. }
  289. func (b *HTTPRequest) buildURL(paramBody string) {
  290. // build GET url with query string
  291. if b.req.Method == "GET" && len(paramBody) > 0 {
  292. if strings.Contains(b.url, "?") {
  293. b.url += "&" + paramBody
  294. } else {
  295. b.url = b.url + "?" + paramBody
  296. }
  297. return
  298. }
  299. // build POST/PUT/PATCH url and body
  300. if (b.req.Method == "POST" || b.req.Method == "PUT" || b.req.Method == "PATCH" || b.req.Method == "DELETE") && b.req.Body == nil {
  301. // with files
  302. if len(b.files) > 0 {
  303. pr, pw := io.Pipe()
  304. bodyWriter := multipart.NewWriter(pw)
  305. go func() {
  306. for formname, filename := range b.files {
  307. fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
  308. if err != nil {
  309. log.Println("Httplib:", err)
  310. }
  311. fh, err := os.Open(filename)
  312. if err != nil {
  313. log.Println("Httplib:", err)
  314. }
  315. //iocopy
  316. _, err = io.Copy(fileWriter, fh)
  317. fh.Close()
  318. if err != nil {
  319. log.Println("Httplib:", err)
  320. }
  321. }
  322. for k, v := range b.params {
  323. for _, vv := range v {
  324. bodyWriter.WriteField(k, vv)
  325. }
  326. }
  327. bodyWriter.Close()
  328. pw.Close()
  329. }()
  330. b.Header("Content-Type", bodyWriter.FormDataContentType())
  331. b.req.Body = ioutil.NopCloser(pr)
  332. return
  333. }
  334. // with params
  335. if len(paramBody) > 0 {
  336. b.Header("Content-Type", "application/x-www-form-urlencoded")
  337. b.Body(paramBody)
  338. }
  339. }
  340. }
  341. func (b *HTTPRequest) getResponse() (*http.Response, error) {
  342. if b.resp.StatusCode != 0 {
  343. return b.resp, nil
  344. }
  345. resp, err := b.DoRequest()
  346. if err != nil {
  347. return nil, err
  348. }
  349. b.resp = resp
  350. return resp, nil
  351. }
  352. // DoRequest will do the client.Do
  353. func (b *HTTPRequest) DoRequest() (resp *http.Response, err error) {
  354. var paramBody string
  355. if len(b.params) > 0 {
  356. var buf bytes.Buffer
  357. for k, v := range b.params {
  358. for _, vv := range v {
  359. buf.WriteString(url.QueryEscape(k))
  360. buf.WriteByte('=')
  361. buf.WriteString(url.QueryEscape(vv))
  362. buf.WriteByte('&')
  363. }
  364. }
  365. paramBody = buf.String()
  366. paramBody = paramBody[0 : len(paramBody)-1]
  367. }
  368. b.buildURL(paramBody)
  369. url, err := url.Parse(b.url)
  370. if err != nil {
  371. return nil, err
  372. }
  373. b.req.URL = url
  374. trans := b.setting.Transport
  375. if trans == nil {
  376. // create default transport
  377. trans = &http.Transport{
  378. TLSClientConfig: b.setting.TLSClientConfig,
  379. Proxy: b.setting.Proxy,
  380. DialContext: (&net.Dialer{
  381. Timeout: b.setting.ConnectTimeout,
  382. KeepAlive: b.setting.KeepAlive,
  383. }).DialContext,
  384. MaxIdleConnsPerHost: -1,
  385. }
  386. } else {
  387. // if b.transport is *http.Transport then set the settings.
  388. if t, ok := trans.(*http.Transport); ok {
  389. if t.TLSClientConfig == nil {
  390. t.TLSClientConfig = b.setting.TLSClientConfig
  391. }
  392. if t.Proxy == nil {
  393. t.Proxy = b.setting.Proxy
  394. }
  395. if t.DialContext == nil {
  396. t.DialContext = (&net.Dialer{
  397. Timeout: b.setting.ConnectTimeout,
  398. KeepAlive: b.setting.KeepAlive,
  399. }).DialContext
  400. }
  401. }
  402. }
  403. var jar http.CookieJar
  404. if b.setting.EnableCookie {
  405. if defaultCookieJar == nil {
  406. createDefaultCookie()
  407. }
  408. jar = defaultCookieJar
  409. }
  410. client := &http.Client{
  411. Transport: trans,
  412. Jar: jar,
  413. }
  414. client.Timeout = b.setting.Timeout
  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 *HTTPRequest) 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 *HTTPRequest) 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. return b.body, err
  469. }
  470. b.body, err = ioutil.ReadAll(resp.Body)
  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 *HTTPRequest) 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 *HTTPRequest) 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 *HTTPRequest) 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 *HTTPRequest) Response() (*http.Response, error) {
  512. return b.getResponse()
  513. }