client.go 6.0 KB

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