client.go 6.0 KB

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