httplib.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  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. func (b *HTTPRequest) GetQueryParam() map[string][]string {
  257. return b.params
  258. }
  259. // PostFile add a post file to the request
  260. func (b *HTTPRequest) PostFile(formname, filename string) *HTTPRequest {
  261. b.files[formname] = filename
  262. return b
  263. }
  264. // Body adds request raw body.
  265. // it supports string and []byte.
  266. func (b *HTTPRequest) Body(data interface{}) *HTTPRequest {
  267. switch t := data.(type) {
  268. case string:
  269. bf := bytes.NewBufferString(t)
  270. b.req.Body = ioutil.NopCloser(bf)
  271. b.req.ContentLength = int64(len(t))
  272. case []byte:
  273. bf := bytes.NewBuffer(t)
  274. b.req.Body = ioutil.NopCloser(bf)
  275. b.req.ContentLength = int64(len(t))
  276. }
  277. return b
  278. }
  279. // JSONBody adds request raw body encoding by JSON.
  280. func (b *HTTPRequest) JSONBody(obj interface{}) (*HTTPRequest, error) {
  281. if b.req.Body == nil && obj != nil {
  282. byts, err := json.Marshal(obj)
  283. if err != nil {
  284. return b, err
  285. }
  286. b.req.Body = ioutil.NopCloser(bytes.NewReader(byts))
  287. b.req.ContentLength = int64(len(byts))
  288. b.req.Header.Set("Content-Type", "application/json")
  289. }
  290. return b, nil
  291. }
  292. func (b *HTTPRequest) buildURL(paramBody string) {
  293. // build GET url with query string
  294. if len(paramBody) > 0 {
  295. //if b.req.Method == "GET" && len(paramBody) > 0 {
  296. if strings.Contains(b.url, "?") {
  297. b.url += "&" + paramBody
  298. } else {
  299. b.url = b.url + "?" + paramBody
  300. }
  301. //return
  302. }
  303. // build POST/PUT/PATCH url and body
  304. if (b.req.Method == "POST" || b.req.Method == "PUT" || b.req.Method == "PATCH" || b.req.Method == "DELETE") && b.req.Body == nil {
  305. // with files
  306. if len(b.files) > 0 {
  307. pr, pw := io.Pipe()
  308. bodyWriter := multipart.NewWriter(pw)
  309. go func() {
  310. for formname, filename := range b.files {
  311. fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
  312. if err != nil {
  313. log.Println("Httplib:", err)
  314. }
  315. fh, err := os.Open(filename)
  316. if err != nil {
  317. log.Println("Httplib:", err)
  318. }
  319. //iocopy
  320. _, err = io.Copy(fileWriter, fh)
  321. fh.Close()
  322. if err != nil {
  323. log.Println("Httplib:", err)
  324. }
  325. }
  326. for k, v := range b.params {
  327. for _, vv := range v {
  328. bodyWriter.WriteField(k, vv)
  329. }
  330. }
  331. bodyWriter.Close()
  332. pw.Close()
  333. }()
  334. b.Header("Content-Type", bodyWriter.FormDataContentType())
  335. b.req.Body = ioutil.NopCloser(pr)
  336. return
  337. }
  338. // with params
  339. if len(paramBody) > 0 {
  340. b.Header("Content-Type", "application/x-www-form-urlencoded")
  341. b.Body(paramBody)
  342. }
  343. }
  344. }
  345. func (b *HTTPRequest) getResponse() (*http.Response, error) {
  346. if b.resp.StatusCode != 0 {
  347. return b.resp, nil
  348. }
  349. resp, err := b.DoRequest()
  350. if err != nil {
  351. return nil, err
  352. }
  353. b.resp = resp
  354. return resp, nil
  355. }
  356. // DoRequest will do the client.Do
  357. func (b *HTTPRequest) DoRequest() (resp *http.Response, err error) {
  358. var paramBody string
  359. if len(b.params) > 0 {
  360. var buf bytes.Buffer
  361. for k, v := range b.params {
  362. for _, vv := range v {
  363. buf.WriteString(url.QueryEscape(k))
  364. buf.WriteByte('=')
  365. buf.WriteString(url.QueryEscape(vv))
  366. buf.WriteByte('&')
  367. }
  368. }
  369. paramBody = buf.String()
  370. paramBody = paramBody[0 : len(paramBody)-1]
  371. }
  372. b.buildURL(paramBody)
  373. url, err := url.Parse(b.url)
  374. if err != nil {
  375. return nil, err
  376. }
  377. b.req.URL = url
  378. trans := b.setting.Transport
  379. if trans == nil {
  380. // create default transport
  381. trans = &http.Transport{
  382. TLSClientConfig: b.setting.TLSClientConfig,
  383. Proxy: b.setting.Proxy,
  384. DialContext: (&net.Dialer{
  385. Timeout: b.setting.ConnectTimeout,
  386. KeepAlive: b.setting.KeepAlive,
  387. }).DialContext,
  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.DialContext == nil {
  400. t.DialContext = (&net.Dialer{
  401. Timeout: b.setting.ConnectTimeout,
  402. KeepAlive: b.setting.KeepAlive,
  403. }).DialContext
  404. }
  405. }
  406. }
  407. var jar http.CookieJar
  408. if b.setting.EnableCookie {
  409. if defaultCookieJar == nil {
  410. createDefaultCookie()
  411. }
  412. jar = defaultCookieJar
  413. }
  414. client := &http.Client{
  415. Transport: trans,
  416. Jar: jar,
  417. }
  418. client.Timeout = b.setting.Timeout
  419. if b.setting.UserAgent != "" && b.req.Header.Get("User-Agent") == "" {
  420. b.req.Header.Set("User-Agent", b.setting.UserAgent)
  421. }
  422. if b.setting.CheckRedirect != nil {
  423. client.CheckRedirect = b.setting.CheckRedirect
  424. }
  425. if b.setting.ShowDebug {
  426. dump, err := httputil.DumpRequest(b.req, b.setting.DumpBody)
  427. if err != nil {
  428. log.Println(err.Error())
  429. }
  430. b.dump = dump
  431. }
  432. // retries default value is 0, it will run once.
  433. // retries equal to -1, it will run forever until success
  434. // retries is setted, it will retries fixed times.
  435. for i := 0; b.setting.Retries == -1 || i <= b.setting.Retries; i++ {
  436. resp, err = client.Do(b.req)
  437. if err == nil {
  438. break
  439. }
  440. }
  441. return resp, err
  442. }
  443. // String returns the body string in response.
  444. // it calls Response inner.
  445. func (b *HTTPRequest) String() (string, error) {
  446. data, err := b.Bytes()
  447. if err != nil {
  448. return "", err
  449. }
  450. return string(data), nil
  451. }
  452. // Bytes returns the body []byte in response.
  453. // it calls Response inner.
  454. func (b *HTTPRequest) Bytes() ([]byte, error) {
  455. if b.body != nil {
  456. return b.body, nil
  457. }
  458. resp, err := b.getResponse()
  459. if err != nil {
  460. return nil, err
  461. }
  462. if resp.Body == nil {
  463. return nil, nil
  464. }
  465. defer resp.Body.Close()
  466. if b.setting.Gzip && resp.Header.Get("Content-Encoding") == "gzip" {
  467. reader, err := gzip.NewReader(resp.Body)
  468. if err != nil {
  469. return nil, err
  470. }
  471. b.body, err = ioutil.ReadAll(reader)
  472. return b.body, err
  473. }
  474. b.body, err = ioutil.ReadAll(resp.Body)
  475. return b.body, err
  476. }
  477. // ToFile saves the body data in response to one file.
  478. // it calls Response inner.
  479. func (b *HTTPRequest) ToFile(filename string) error {
  480. f, err := os.Create(filename)
  481. if err != nil {
  482. return err
  483. }
  484. defer f.Close()
  485. resp, err := b.getResponse()
  486. if err != nil {
  487. return err
  488. }
  489. if resp.Body == nil {
  490. return nil
  491. }
  492. defer resp.Body.Close()
  493. _, err = io.Copy(f, resp.Body)
  494. return err
  495. }
  496. // ToJSON returns the map that marshals from the body bytes as json in response .
  497. // it calls Response inner.
  498. func (b *HTTPRequest) ToJSON(v interface{}) error {
  499. data, err := b.Bytes()
  500. println(string(data))
  501. if err != nil {
  502. return err
  503. }
  504. return json.Unmarshal(data, v)
  505. }
  506. // ToXML returns the map that marshals from the body bytes as xml in response .
  507. // it calls Response inner.
  508. func (b *HTTPRequest) ToXML(v interface{}) error {
  509. data, err := b.Bytes()
  510. if err != nil {
  511. return err
  512. }
  513. return xml.Unmarshal(data, v)
  514. }
  515. // Response executes request client gets response mannually.
  516. func (b *HTTPRequest) Response() (*http.Response, error) {
  517. return b.getResponse()
  518. }