httplib.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. // Copyright 2013 The Beego Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package httplib
  6. import (
  7. "bytes"
  8. "context"
  9. "crypto/tls"
  10. "encoding/xml"
  11. "io"
  12. "io/ioutil"
  13. "log"
  14. "mime/multipart"
  15. "net"
  16. "net/http"
  17. "net/http/cookiejar"
  18. "net/http/httputil"
  19. "net/url"
  20. "os"
  21. "strings"
  22. "sync"
  23. "time"
  24. jsoniter "github.com/json-iterator/go"
  25. )
  26. var defaultSetting = Settings{false, "GogsServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false}
  27. var defaultCookieJar http.CookieJar
  28. var settingMutex sync.Mutex
  29. // createDefaultCookie creates a global cookiejar to store cookies.
  30. func createDefaultCookie() {
  31. settingMutex.Lock()
  32. defer settingMutex.Unlock()
  33. defaultCookieJar, _ = cookiejar.New(nil)
  34. }
  35. // Overwrite default settings
  36. func SetDefaultSetting(setting Settings) {
  37. settingMutex.Lock()
  38. defer settingMutex.Unlock()
  39. defaultSetting = setting
  40. if defaultSetting.ConnectTimeout == 0 {
  41. defaultSetting.ConnectTimeout = 60 * time.Second
  42. }
  43. if defaultSetting.ReadWriteTimeout == 0 {
  44. defaultSetting.ReadWriteTimeout = 60 * time.Second
  45. }
  46. }
  47. // return *Request with specific method
  48. func newRequest(url, method string) *Request {
  49. var resp http.Response
  50. req := http.Request{
  51. Method: method,
  52. Header: make(http.Header),
  53. Proto: "HTTP/1.1",
  54. ProtoMajor: 1,
  55. ProtoMinor: 1,
  56. }
  57. return &Request{url, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil}
  58. }
  59. // Get returns *Request with GET method.
  60. func Get(url string) *Request {
  61. return newRequest(url, "GET")
  62. }
  63. // Post returns *Request with POST method.
  64. func Post(url string) *Request {
  65. return newRequest(url, "POST")
  66. }
  67. // Put returns *Request with PUT method.
  68. func Put(url string) *Request {
  69. return newRequest(url, "PUT")
  70. }
  71. // Delete returns *Request DELETE method.
  72. func Delete(url string) *Request {
  73. return newRequest(url, "DELETE")
  74. }
  75. // Head returns *Request with HEAD method.
  76. func Head(url string) *Request {
  77. return newRequest(url, "HEAD")
  78. }
  79. type Settings struct {
  80. ShowDebug bool
  81. UserAgent string
  82. ConnectTimeout time.Duration
  83. ReadWriteTimeout time.Duration
  84. TlsClientConfig *tls.Config
  85. Proxy func(*http.Request) (*url.URL, error)
  86. Transport http.RoundTripper
  87. EnableCookie bool
  88. }
  89. // HttpRequest provides more useful methods for requesting one url than http.Request.
  90. type Request struct {
  91. url string
  92. req *http.Request
  93. params map[string]string
  94. files map[string]string
  95. setting Settings
  96. resp *http.Response
  97. body []byte
  98. }
  99. // Change request settings
  100. func (r *Request) Setting(setting Settings) *Request {
  101. r.setting = setting
  102. return r
  103. }
  104. // SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
  105. func (r *Request) SetBasicAuth(username, password string) *Request {
  106. r.req.SetBasicAuth(username, password)
  107. return r
  108. }
  109. // SetEnableCookie sets enable/disable cookiejar
  110. func (r *Request) SetEnableCookie(enable bool) *Request {
  111. r.setting.EnableCookie = enable
  112. return r
  113. }
  114. // SetUserAgent sets User-Agent header field
  115. func (r *Request) SetUserAgent(useragent string) *Request {
  116. r.setting.UserAgent = useragent
  117. return r
  118. }
  119. // Debug sets show debug or not when executing request.
  120. func (r *Request) Debug(isdebug bool) *Request {
  121. r.setting.ShowDebug = isdebug
  122. return r
  123. }
  124. // SetTimeout sets connect time out and read-write time out for Request.
  125. func (r *Request) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *Request {
  126. r.setting.ConnectTimeout = connectTimeout
  127. r.setting.ReadWriteTimeout = readWriteTimeout
  128. return r
  129. }
  130. // SetTLSClientConfig sets tls connection configurations if visiting https url.
  131. func (r *Request) SetTLSClientConfig(config *tls.Config) *Request {
  132. r.setting.TlsClientConfig = config
  133. return r
  134. }
  135. // Header add header item string in request.
  136. func (r *Request) Header(key, value string) *Request {
  137. r.req.Header.Set(key, value)
  138. return r
  139. }
  140. func (r *Request) Headers() http.Header {
  141. return r.req.Header
  142. }
  143. // Set the protocol version for incoming requests.
  144. // Client requests always use HTTP/1.1.
  145. func (r *Request) SetProtocolVersion(vers string) *Request {
  146. if len(vers) == 0 {
  147. vers = "HTTP/1.1"
  148. }
  149. major, minor, ok := http.ParseHTTPVersion(vers)
  150. if ok {
  151. r.req.Proto = vers
  152. r.req.ProtoMajor = major
  153. r.req.ProtoMinor = minor
  154. }
  155. return r
  156. }
  157. // SetCookie add cookie into request.
  158. func (r *Request) SetCookie(cookie *http.Cookie) *Request {
  159. r.req.Header.Add("Cookie", cookie.String())
  160. return r
  161. }
  162. // Set transport to
  163. func (r *Request) SetTransport(transport http.RoundTripper) *Request {
  164. r.setting.Transport = transport
  165. return r
  166. }
  167. // Set http proxy
  168. // example:
  169. //
  170. // func(req *http.Request) (*url.URL, error) {
  171. // u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
  172. // return u, nil
  173. // }
  174. func (r *Request) SetProxy(proxy func(*http.Request) (*url.URL, error)) *Request {
  175. r.setting.Proxy = proxy
  176. return r
  177. }
  178. // Param adds query param in to request.
  179. // params build query string as ?key1=value1&key2=value2...
  180. func (r *Request) Param(key, value string) *Request {
  181. r.params[key] = value
  182. return r
  183. }
  184. func (r *Request) PostFile(formname, filename string) *Request {
  185. r.files[formname] = filename
  186. return r
  187. }
  188. // Body adds request raw body.
  189. // it supports string and []byte.
  190. func (r *Request) Body(data interface{}) *Request {
  191. switch t := data.(type) {
  192. case string:
  193. bf := bytes.NewBufferString(t)
  194. r.req.Body = ioutil.NopCloser(bf)
  195. r.req.ContentLength = int64(len(t))
  196. case []byte:
  197. bf := bytes.NewBuffer(t)
  198. r.req.Body = ioutil.NopCloser(bf)
  199. r.req.ContentLength = int64(len(t))
  200. }
  201. return r
  202. }
  203. func (r *Request) getResponse() (*http.Response, error) {
  204. if r.resp.StatusCode != 0 {
  205. return r.resp, nil
  206. }
  207. var paramBody string
  208. if len(r.params) > 0 {
  209. var buf bytes.Buffer
  210. for k, v := range r.params {
  211. buf.WriteString(url.QueryEscape(k))
  212. buf.WriteByte('=')
  213. buf.WriteString(url.QueryEscape(v))
  214. buf.WriteByte('&')
  215. }
  216. paramBody = buf.String()
  217. paramBody = paramBody[0 : len(paramBody)-1]
  218. }
  219. if r.req.Method == "GET" && len(paramBody) > 0 {
  220. if strings.Contains(r.url, "?") {
  221. r.url += "&" + paramBody
  222. } else {
  223. r.url = r.url + "?" + paramBody
  224. }
  225. } else if r.req.Method == "POST" && r.req.Body == nil {
  226. if len(r.files) > 0 {
  227. pr, pw := io.Pipe()
  228. bodyWriter := multipart.NewWriter(pw)
  229. go func() {
  230. for formname, filename := range r.files {
  231. fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
  232. if err != nil {
  233. log.Fatal(err)
  234. }
  235. fh, err := os.Open(filename)
  236. if err != nil {
  237. log.Fatal(err)
  238. }
  239. // iocopy
  240. _, err = io.Copy(fileWriter, fh)
  241. _ = fh.Close()
  242. if err != nil {
  243. log.Fatal(err)
  244. }
  245. }
  246. for k, v := range r.params {
  247. _ = bodyWriter.WriteField(k, v)
  248. }
  249. _ = bodyWriter.Close()
  250. _ = pw.Close()
  251. }()
  252. r.Header("Content-Type", bodyWriter.FormDataContentType())
  253. r.req.Body = ioutil.NopCloser(pr)
  254. } else if len(paramBody) > 0 {
  255. r.Header("Content-Type", "application/x-www-form-urlencoded")
  256. r.Body(paramBody)
  257. }
  258. }
  259. url, err := url.Parse(r.url)
  260. if err != nil {
  261. return nil, err
  262. }
  263. r.req.URL = url
  264. trans := r.setting.Transport
  265. if trans == nil {
  266. // create default transport
  267. trans = &http.Transport{
  268. TLSClientConfig: r.setting.TlsClientConfig,
  269. Proxy: r.setting.Proxy,
  270. DialContext: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout),
  271. }
  272. } else {
  273. // if r.transport is *http.Transport then set the settings.
  274. if t, ok := trans.(*http.Transport); ok {
  275. if t.TLSClientConfig == nil {
  276. t.TLSClientConfig = r.setting.TlsClientConfig
  277. }
  278. if t.Proxy == nil {
  279. t.Proxy = r.setting.Proxy
  280. }
  281. if t.DialContext == nil {
  282. t.DialContext = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout)
  283. }
  284. }
  285. }
  286. var jar http.CookieJar
  287. if r.setting.EnableCookie {
  288. if defaultCookieJar == nil {
  289. createDefaultCookie()
  290. }
  291. jar = defaultCookieJar
  292. } else {
  293. jar = nil
  294. }
  295. client := &http.Client{
  296. Transport: trans,
  297. Jar: jar,
  298. }
  299. if len(r.setting.UserAgent) > 0 && len(r.req.Header.Get("User-Agent")) == 0 {
  300. r.req.Header.Set("User-Agent", r.setting.UserAgent)
  301. }
  302. if r.setting.ShowDebug {
  303. dump, err := httputil.DumpRequest(r.req, true)
  304. if err != nil {
  305. println(err.Error())
  306. }
  307. println(string(dump))
  308. }
  309. resp, err := client.Do(r.req)
  310. if err != nil {
  311. return nil, err
  312. }
  313. r.resp = resp
  314. return resp, nil
  315. }
  316. // String returns the body string in response.
  317. // it calls Response inner.
  318. func (r *Request) String() (string, error) {
  319. data, err := r.Bytes()
  320. if err != nil {
  321. return "", err
  322. }
  323. return string(data), nil
  324. }
  325. // Bytes returns the body []byte in response.
  326. // it calls Response inner.
  327. func (r *Request) Bytes() ([]byte, error) {
  328. if r.body != nil {
  329. return r.body, nil
  330. }
  331. resp, err := r.getResponse()
  332. if err != nil {
  333. return nil, err
  334. }
  335. if resp.Body == nil {
  336. return nil, nil
  337. }
  338. defer resp.Body.Close()
  339. data, err := ioutil.ReadAll(resp.Body)
  340. if err != nil {
  341. return nil, err
  342. }
  343. r.body = data
  344. return data, nil
  345. }
  346. // ToFile saves the body data in response to one file.
  347. // it calls Response inner.
  348. func (r *Request) ToFile(filename string) error {
  349. f, err := os.Create(filename)
  350. if err != nil {
  351. return err
  352. }
  353. defer f.Close()
  354. resp, err := r.getResponse()
  355. if err != nil {
  356. return err
  357. }
  358. if resp.Body == nil {
  359. return nil
  360. }
  361. defer resp.Body.Close()
  362. _, err = io.Copy(f, resp.Body)
  363. return err
  364. }
  365. // ToJson returns the map that marshals from the body bytes as json in response .
  366. // it calls Response inner.
  367. func (r *Request) ToJson(v interface{}) error {
  368. data, err := r.Bytes()
  369. if err != nil {
  370. return err
  371. }
  372. return jsoniter.Unmarshal(data, v)
  373. }
  374. // ToXml returns the map that marshals from the body bytes as xml in response .
  375. // it calls Response inner.
  376. func (r *Request) ToXml(v interface{}) error {
  377. data, err := r.Bytes()
  378. if err != nil {
  379. return err
  380. }
  381. return xml.Unmarshal(data, v)
  382. }
  383. // Response executes request client gets response mannually.
  384. func (r *Request) Response() (*http.Response, error) {
  385. return r.getResponse()
  386. }
  387. // TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.
  388. func TimeoutDialer(cTimeout time.Duration, rwTimeout time.Duration) func(ctx context.Context, net, addr string) (c net.Conn, err error) {
  389. return func(ctx context.Context, netw, addr string) (net.Conn, error) {
  390. conn, err := net.DialTimeout(netw, addr, cTimeout)
  391. if err != nil {
  392. return nil, err
  393. }
  394. return conn, conn.SetDeadline(time.Now().Add(rwTimeout))
  395. }
  396. }