You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

446 lines
11 KiB

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