client.go 6.1 KB

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