client.go 8.8 KB

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