http.go 16 KB

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