client.go 8.7 KB

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