client.go 8.5 KB

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