client.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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 resp != nil {
  97. defer resp.Body.Close()
  98. }
  99. if err != nil {
  100. if uerr, ok := err.(*url.Error); ok {
  101. switch uerr.Err.(type) {
  102. case x509.CertificateInvalidError, x509.HostnameError:
  103. err = errors.NewLocalizedError(errInvalidCertificate, uerr.Err)
  104. case *net.OpError:
  105. if uerr.Err.(*net.OpError).Temporary() {
  106. err = errors.NewLocalizedError(errTemporaryNetworkOperation, uerr.Err)
  107. } else {
  108. err = errors.NewLocalizedError(errPermanentNetworkOperation, uerr.Err)
  109. }
  110. case net.Error:
  111. nerr := uerr.Err.(net.Error)
  112. if nerr.Timeout() {
  113. err = errors.NewLocalizedError(errRequestTimeout, requestTimeout)
  114. } else if nerr.Temporary() {
  115. err = errors.NewLocalizedError(errTemporaryNetworkOperation, nerr)
  116. }
  117. }
  118. }
  119. return nil, err
  120. }
  121. if resp.ContentLength > maxBodySize {
  122. return nil, fmt.Errorf("client: response too large (%d bytes)", resp.ContentLength)
  123. }
  124. buf, err := ioutil.ReadAll(resp.Body)
  125. if err != nil {
  126. return nil, fmt.Errorf("client: error while reading body %v", err)
  127. }
  128. response := &Response{
  129. Body: bytes.NewReader(buf),
  130. StatusCode: resp.StatusCode,
  131. EffectiveURL: resp.Request.URL.String(),
  132. LastModified: resp.Header.Get("Last-Modified"),
  133. ETag: resp.Header.Get("ETag"),
  134. ContentType: resp.Header.Get("Content-Type"),
  135. ContentLength: resp.ContentLength,
  136. }
  137. logger.Debug("[HttpClient:%s] URL=%s, EffectiveURL=%s, Code=%d, Length=%d, Type=%s, ETag=%s, LastMod=%s, Expires=%s",
  138. request.Method,
  139. c.url,
  140. response.EffectiveURL,
  141. response.StatusCode,
  142. resp.ContentLength,
  143. response.ContentType,
  144. response.ETag,
  145. response.LastModified,
  146. resp.Header.Get("Expires"),
  147. )
  148. // Ignore caching headers for feeds that do not want any cache.
  149. if resp.Header.Get("Expires") == "0" {
  150. logger.Debug("[HttpClient] Ignore caching headers for %q", response.EffectiveURL)
  151. response.ETag = ""
  152. response.LastModified = ""
  153. }
  154. return response, err
  155. }
  156. func (c *Client) buildRequest(method string, body io.Reader) (*http.Request, error) {
  157. request, err := http.NewRequest(method, c.url, body)
  158. if err != nil {
  159. return nil, err
  160. }
  161. request.Header = c.buildHeaders()
  162. if c.username != "" && c.password != "" {
  163. request.SetBasicAuth(c.username, c.password)
  164. }
  165. return request, nil
  166. }
  167. func (c *Client) buildClient() http.Client {
  168. client := http.Client{Timeout: time.Duration(requestTimeout * time.Second)}
  169. if c.Insecure {
  170. client.Transport = &http.Transport{
  171. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  172. }
  173. }
  174. return client
  175. }
  176. func (c *Client) buildHeaders() http.Header {
  177. headers := make(http.Header)
  178. headers.Add("User-Agent", "Mozilla/5.0 (compatible; Miniflux/"+version.Version+"; +https://miniflux.net)")
  179. headers.Add("Accept", "*/*")
  180. if c.etagHeader != "" {
  181. headers.Add("If-None-Match", c.etagHeader)
  182. }
  183. if c.lastModifiedHeader != "" {
  184. headers.Add("If-Modified-Since", c.lastModifiedHeader)
  185. }
  186. if c.authorizationHeader != "" {
  187. headers.Add("Authorization", c.authorizationHeader)
  188. }
  189. headers.Add("Connection", "close")
  190. return headers
  191. }
  192. // New returns a new HTTP client.
  193. func New(url string) *Client {
  194. return &Client{url: url, Insecure: false}
  195. }