client.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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/errors"
  19. "miniflux.app/logger"
  20. "miniflux.app/timer"
  21. "miniflux.app/version"
  22. )
  23. const (
  24. // 20 seconds max.
  25. requestTimeout = 20
  26. // 15MB max.
  27. maxBodySize = 1024 * 1024 * 15
  28. )
  29. var (
  30. // DefaultUserAgent sets the User-Agent header used for any requests by miniflux.
  31. DefaultUserAgent = "Mozilla/5.0 (compatible; Miniflux/" + version.Version + "; +https://miniflux.app)"
  32. errInvalidCertificate = "Invalid SSL certificate (original error: %q)"
  33. errTemporaryNetworkOperation = "This website is temporarily unreachable (original error: %q)"
  34. errPermanentNetworkOperation = "This website is permanently unreachable (original error: %q)"
  35. errRequestTimeout = "Website unreachable, the request timed out after %d seconds"
  36. )
  37. // Client is a HTTP Client :)
  38. type Client struct {
  39. url string
  40. etagHeader string
  41. lastModifiedHeader string
  42. authorizationHeader string
  43. username string
  44. password string
  45. userAgent string
  46. Insecure bool
  47. }
  48. // WithCredentials defines the username/password for HTTP Basic authentication.
  49. func (c *Client) WithCredentials(username, password string) *Client {
  50. if username != "" && password != "" {
  51. c.username = username
  52. c.password = password
  53. }
  54. return c
  55. }
  56. // WithAuthorization defines authorization header value.
  57. func (c *Client) WithAuthorization(authorization string) *Client {
  58. c.authorizationHeader = authorization
  59. return c
  60. }
  61. // WithCacheHeaders defines caching headers.
  62. func (c *Client) WithCacheHeaders(etagHeader, lastModifiedHeader string) *Client {
  63. c.etagHeader = etagHeader
  64. c.lastModifiedHeader = lastModifiedHeader
  65. return c
  66. }
  67. // WithUserAgent defines the User-Agent header to use for outgoing requests.
  68. func (c *Client) WithUserAgent(userAgent string) *Client {
  69. if userAgent != "" {
  70. c.userAgent = userAgent
  71. }
  72. return c
  73. }
  74. // Get execute a GET HTTP request.
  75. func (c *Client) Get() (*Response, error) {
  76. request, err := c.buildRequest(http.MethodGet, nil)
  77. if err != nil {
  78. return nil, err
  79. }
  80. return c.executeRequest(request)
  81. }
  82. // PostForm execute a POST HTTP request with form values.
  83. func (c *Client) PostForm(values url.Values) (*Response, error) {
  84. request, err := c.buildRequest(http.MethodPost, strings.NewReader(values.Encode()))
  85. if err != nil {
  86. return nil, err
  87. }
  88. request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  89. return c.executeRequest(request)
  90. }
  91. // PostJSON execute a POST HTTP request with JSON payload.
  92. func (c *Client) PostJSON(data interface{}) (*Response, error) {
  93. b, err := json.Marshal(data)
  94. if err != nil {
  95. return nil, err
  96. }
  97. request, err := c.buildRequest(http.MethodPost, bytes.NewReader(b))
  98. if err != nil {
  99. return nil, err
  100. }
  101. request.Header.Add("Content-Type", "application/json")
  102. return c.executeRequest(request)
  103. }
  104. func (c *Client) executeRequest(request *http.Request) (*Response, error) {
  105. defer timer.ExecutionTime(time.Now(), fmt.Sprintf("[HttpClient] url=%s", c.url))
  106. client := c.buildClient()
  107. resp, err := client.Do(request)
  108. if resp != nil {
  109. defer resp.Body.Close()
  110. }
  111. if err != nil {
  112. if uerr, ok := err.(*url.Error); ok {
  113. switch uerr.Err.(type) {
  114. case x509.CertificateInvalidError, x509.HostnameError:
  115. err = errors.NewLocalizedError(errInvalidCertificate, uerr.Err)
  116. case *net.OpError:
  117. if uerr.Err.(*net.OpError).Temporary() {
  118. err = errors.NewLocalizedError(errTemporaryNetworkOperation, uerr.Err)
  119. } else {
  120. err = errors.NewLocalizedError(errPermanentNetworkOperation, uerr.Err)
  121. }
  122. case net.Error:
  123. nerr := uerr.Err.(net.Error)
  124. if nerr.Timeout() {
  125. err = errors.NewLocalizedError(errRequestTimeout, requestTimeout)
  126. } else if nerr.Temporary() {
  127. err = errors.NewLocalizedError(errTemporaryNetworkOperation, nerr)
  128. }
  129. }
  130. }
  131. return nil, err
  132. }
  133. if resp.ContentLength > maxBodySize {
  134. return nil, fmt.Errorf("client: response too large (%d bytes)", resp.ContentLength)
  135. }
  136. buf, err := ioutil.ReadAll(resp.Body)
  137. if err != nil {
  138. return nil, fmt.Errorf("client: error while reading body %v", err)
  139. }
  140. response := &Response{
  141. Body: bytes.NewReader(buf),
  142. StatusCode: resp.StatusCode,
  143. EffectiveURL: resp.Request.URL.String(),
  144. LastModified: resp.Header.Get("Last-Modified"),
  145. ETag: resp.Header.Get("ETag"),
  146. ContentType: resp.Header.Get("Content-Type"),
  147. ContentLength: resp.ContentLength,
  148. }
  149. logger.Debug("[HttpClient:%s] URL=%s, EffectiveURL=%s, Code=%d, Length=%d, Type=%s, ETag=%s, LastMod=%s, Expires=%s, Auth=%v",
  150. request.Method,
  151. c.url,
  152. response.EffectiveURL,
  153. response.StatusCode,
  154. resp.ContentLength,
  155. response.ContentType,
  156. response.ETag,
  157. response.LastModified,
  158. resp.Header.Get("Expires"),
  159. c.username != "",
  160. )
  161. // Ignore caching headers for feeds that do not want any cache.
  162. if resp.Header.Get("Expires") == "0" {
  163. logger.Debug("[HttpClient] Ignore caching headers for %q", response.EffectiveURL)
  164. response.ETag = ""
  165. response.LastModified = ""
  166. }
  167. return response, err
  168. }
  169. func (c *Client) buildRequest(method string, body io.Reader) (*http.Request, error) {
  170. request, err := http.NewRequest(method, c.url, body)
  171. if err != nil {
  172. return nil, err
  173. }
  174. request.Header = c.buildHeaders()
  175. if c.username != "" && c.password != "" {
  176. request.SetBasicAuth(c.username, c.password)
  177. }
  178. return request, nil
  179. }
  180. func (c *Client) buildClient() http.Client {
  181. client := http.Client{Timeout: time.Duration(requestTimeout * time.Second)}
  182. if c.Insecure {
  183. client.Transport = &http.Transport{
  184. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  185. }
  186. }
  187. return client
  188. }
  189. func (c *Client) buildHeaders() http.Header {
  190. headers := make(http.Header)
  191. headers.Add("User-Agent", c.userAgent)
  192. headers.Add("Accept", "*/*")
  193. if c.etagHeader != "" {
  194. headers.Add("If-None-Match", c.etagHeader)
  195. }
  196. if c.lastModifiedHeader != "" {
  197. headers.Add("If-Modified-Since", c.lastModifiedHeader)
  198. }
  199. if c.authorizationHeader != "" {
  200. headers.Add("Authorization", c.authorizationHeader)
  201. }
  202. headers.Add("Connection", "close")
  203. return headers
  204. }
  205. // New returns a new HTTP client.
  206. func New(url string) *Client {
  207. return &Client{url: url, userAgent: DefaultUserAgent, Insecure: false}
  208. }