1
0

httplib.go 10 KB

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