client.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package client // import "miniflux.app/http/client"
  5. import (
  6. "bytes"
  7. "crypto/tls"
  8. "crypto/x509"
  9. "encoding/json"
  10. "fmt"
  11. "io"
  12. "io/ioutil"
  13. "net"
  14. "net/http"
  15. "net/url"
  16. "strings"
  17. "time"
  18. "miniflux.app/config"
  19. "miniflux.app/errors"
  20. "miniflux.app/logger"
  21. "miniflux.app/timer"
  22. url_helper "miniflux.app/url"
  23. "miniflux.app/version"
  24. )
  25. var (
  26. // DefaultUserAgent sets the User-Agent header used for any requests by miniflux.
  27. DefaultUserAgent = "Mozilla/5.0 (compatible; Miniflux/" + version.Version + "; +https://miniflux.app)"
  28. errInvalidCertificate = "Invalid SSL certificate (original error: %q)"
  29. errTemporaryNetworkOperation = "This website is temporarily unreachable (original error: %q)"
  30. errPermanentNetworkOperation = "This website is permanently unreachable (original error: %q)"
  31. errRequestTimeout = "Website unreachable, the request timed out after %d seconds"
  32. )
  33. // Client is a HTTP Client :)
  34. type Client struct {
  35. inputURL string
  36. requestURL string
  37. etagHeader string
  38. lastModifiedHeader string
  39. authorizationHeader string
  40. username string
  41. password string
  42. userAgent string
  43. Insecure bool
  44. fetchViaProxy bool
  45. }
  46. func (c *Client) String() string {
  47. etagHeader := c.etagHeader
  48. if c.etagHeader == "" {
  49. etagHeader = "None"
  50. }
  51. lastModifiedHeader := c.lastModifiedHeader
  52. if c.lastModifiedHeader == "" {
  53. lastModifiedHeader = "None"
  54. }
  55. return fmt.Sprintf(
  56. `InputURL=%q RequestURL=%q ETag=%s LastModified=%s BasicAuth=%v UserAgent=%q`,
  57. c.inputURL,
  58. c.requestURL,
  59. etagHeader,
  60. lastModifiedHeader,
  61. c.authorizationHeader != "" || (c.username != "" && c.password != ""),
  62. c.userAgent,
  63. )
  64. }
  65. // WithCredentials defines the username/password for HTTP Basic authentication.
  66. func (c *Client) WithCredentials(username, password string) *Client {
  67. if username != "" && password != "" {
  68. c.username = username
  69. c.password = password
  70. }
  71. return c
  72. }
  73. // WithAuthorization defines authorization header value.
  74. func (c *Client) WithAuthorization(authorization string) *Client {
  75. c.authorizationHeader = authorization
  76. return c
  77. }
  78. // WithCacheHeaders defines caching headers.
  79. func (c *Client) WithCacheHeaders(etagHeader, lastModifiedHeader string) *Client {
  80. c.etagHeader = etagHeader
  81. c.lastModifiedHeader = lastModifiedHeader
  82. return c
  83. }
  84. // WithProxy enable proxy for current HTTP client request.
  85. func (c *Client) WithProxy() *Client {
  86. c.fetchViaProxy = true
  87. return c
  88. }
  89. // WithUserAgent defines the User-Agent header to use for outgoing requests.
  90. func (c *Client) WithUserAgent(userAgent string) *Client {
  91. if userAgent != "" {
  92. c.userAgent = userAgent
  93. }
  94. return c
  95. }
  96. // Get execute a GET HTTP request.
  97. func (c *Client) Get() (*Response, error) {
  98. request, err := c.buildRequest(http.MethodGet, nil)
  99. if err != nil {
  100. return nil, err
  101. }
  102. return c.executeRequest(request)
  103. }
  104. // PostForm execute a POST HTTP request with form values.
  105. func (c *Client) PostForm(values url.Values) (*Response, error) {
  106. request, err := c.buildRequest(http.MethodPost, strings.NewReader(values.Encode()))
  107. if err != nil {
  108. return nil, err
  109. }
  110. request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  111. return c.executeRequest(request)
  112. }
  113. // PostJSON execute a POST HTTP request with JSON payload.
  114. func (c *Client) PostJSON(data interface{}) (*Response, error) {
  115. b, err := json.Marshal(data)
  116. if err != nil {
  117. return nil, err
  118. }
  119. request, err := c.buildRequest(http.MethodPost, bytes.NewReader(b))
  120. if err != nil {
  121. return nil, err
  122. }
  123. request.Header.Add("Content-Type", "application/json")
  124. return c.executeRequest(request)
  125. }
  126. func (c *Client) executeRequest(request *http.Request) (*Response, error) {
  127. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[HttpClient] inputURL=%s", c.inputURL))
  128. logger.Debug("[HttpClient:Before] Method=%s %s",
  129. request.Method,
  130. c.String(),
  131. )
  132. client := c.buildClient()
  133. resp, err := client.Do(request)
  134. if resp != nil {
  135. defer resp.Body.Close()
  136. }
  137. if err != nil {
  138. if uerr, ok := err.(*url.Error); ok {
  139. switch uerr.Err.(type) {
  140. case x509.CertificateInvalidError, x509.HostnameError:
  141. err = errors.NewLocalizedError(errInvalidCertificate, uerr.Err)
  142. case *net.OpError:
  143. if uerr.Err.(*net.OpError).Temporary() {
  144. err = errors.NewLocalizedError(errTemporaryNetworkOperation, uerr.Err)
  145. } else {
  146. err = errors.NewLocalizedError(errPermanentNetworkOperation, uerr.Err)
  147. }
  148. case net.Error:
  149. nerr := uerr.Err.(net.Error)
  150. if nerr.Timeout() {
  151. err = errors.NewLocalizedError(errRequestTimeout, config.Opts.HTTPClientTimeout())
  152. } else if nerr.Temporary() {
  153. err = errors.NewLocalizedError(errTemporaryNetworkOperation, nerr)
  154. }
  155. }
  156. }
  157. return nil, err
  158. }
  159. if resp.ContentLength > config.Opts.HTTPClientMaxBodySize() {
  160. return nil, fmt.Errorf("client: response too large (%d bytes)", resp.ContentLength)
  161. }
  162. buf, err := ioutil.ReadAll(resp.Body)
  163. if err != nil {
  164. return nil, fmt.Errorf("client: error while reading body %v", err)
  165. }
  166. response := &Response{
  167. Body: bytes.NewReader(buf),
  168. StatusCode: resp.StatusCode,
  169. EffectiveURL: resp.Request.URL.String(),
  170. LastModified: resp.Header.Get("Last-Modified"),
  171. ETag: resp.Header.Get("ETag"),
  172. Expires: resp.Header.Get("Expires"),
  173. ContentType: resp.Header.Get("Content-Type"),
  174. ContentLength: resp.ContentLength,
  175. }
  176. logger.Debug("[HttpClient:After] Method=%s %s; Response => %s",
  177. request.Method,
  178. c.String(),
  179. response,
  180. )
  181. // Ignore caching headers for feeds that do not want any cache.
  182. if resp.Header.Get("Expires") == "0" {
  183. logger.Debug("[HttpClient] Ignore caching headers for %q", response.EffectiveURL)
  184. response.ETag = ""
  185. response.LastModified = ""
  186. }
  187. return response, err
  188. }
  189. func (c *Client) buildRequest(method string, body io.Reader) (*http.Request, error) {
  190. c.requestURL = url_helper.RequestURI(c.inputURL)
  191. request, err := http.NewRequest(method, c.requestURL, body)
  192. if err != nil {
  193. return nil, err
  194. }
  195. request.Header = c.buildHeaders()
  196. if c.username != "" && c.password != "" {
  197. request.SetBasicAuth(c.username, c.password)
  198. }
  199. return request, nil
  200. }
  201. func (c *Client) buildClient() http.Client {
  202. client := http.Client{Timeout: time.Duration(config.Opts.HTTPClientTimeout()) * time.Second}
  203. transport := &http.Transport{
  204. DialContext: (&net.Dialer{
  205. // Default is 30s.
  206. Timeout: 10 * time.Second,
  207. // Default is 30s.
  208. KeepAlive: 15 * time.Second,
  209. }).DialContext,
  210. // Default is 100.
  211. MaxIdleConns: 50,
  212. // Default is 90s.
  213. IdleConnTimeout: 10 * time.Second,
  214. }
  215. if c.Insecure {
  216. transport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
  217. }
  218. if c.fetchViaProxy && config.Opts.HasHTTPClientProxyConfigured() {
  219. proxyURL, err := url.Parse(config.Opts.HTTPClientProxy())
  220. if err != nil {
  221. logger.Error("[HttpClient] Proxy URL error: %v", err)
  222. } else {
  223. logger.Debug("[HttpClient] Use proxy: %s", proxyURL)
  224. transport.Proxy = http.ProxyURL(proxyURL)
  225. }
  226. }
  227. client.Transport = transport
  228. return client
  229. }
  230. func (c *Client) buildHeaders() http.Header {
  231. headers := make(http.Header)
  232. headers.Add("User-Agent", c.userAgent)
  233. headers.Add("Accept", "*/*")
  234. if c.etagHeader != "" {
  235. headers.Add("If-None-Match", c.etagHeader)
  236. }
  237. if c.lastModifiedHeader != "" {
  238. headers.Add("If-Modified-Since", c.lastModifiedHeader)
  239. }
  240. if c.authorizationHeader != "" {
  241. headers.Add("Authorization", c.authorizationHeader)
  242. }
  243. headers.Add("Connection", "close")
  244. return headers
  245. }
  246. // New returns a new HTTP client.
  247. func New(url string) *Client {
  248. return &Client{inputURL: url, userAgent: DefaultUserAgent, Insecure: false}
  249. }