client.go 8.5 KB

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