client.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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] OriginalURL=%s, StatusCode=%d, ContentLength=%d, ContentType=%s, ETag=%s, LastModified=%s, EffectiveURL=%s",
  113. request.Method,
  114. c.url,
  115. response.StatusCode,
  116. resp.ContentLength,
  117. response.ContentType,
  118. response.ETag,
  119. response.LastModified,
  120. response.EffectiveURL,
  121. )
  122. return response, err
  123. }
  124. func (c *Client) buildRequest(method string, body io.Reader) (*http.Request, error) {
  125. request, err := http.NewRequest(method, c.url, body)
  126. if err != nil {
  127. return nil, err
  128. }
  129. request.Header = c.buildHeaders()
  130. if c.username != "" && c.password != "" {
  131. request.SetBasicAuth(c.username, c.password)
  132. }
  133. return request, nil
  134. }
  135. func (c *Client) buildClient() http.Client {
  136. client := http.Client{Timeout: time.Duration(requestTimeout * time.Second)}
  137. if c.Insecure {
  138. client.Transport = &http.Transport{
  139. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  140. }
  141. }
  142. return client
  143. }
  144. func (c *Client) buildHeaders() http.Header {
  145. headers := make(http.Header)
  146. headers.Add("User-Agent", "Mozilla/5.0 (compatible; Miniflux/"+version.Version+"; +https://miniflux.net)")
  147. headers.Add("Accept", "*/*")
  148. if c.etagHeader != "" {
  149. headers.Add("If-None-Match", c.etagHeader)
  150. }
  151. if c.lastModifiedHeader != "" {
  152. headers.Add("If-Modified-Since", c.lastModifiedHeader)
  153. }
  154. if c.authorizationHeader != "" {
  155. headers.Add("Authorization", c.authorizationHeader)
  156. }
  157. return headers
  158. }
  159. // NewClient returns a new HTTP client.
  160. func NewClient(url string) *Client {
  161. return &Client{url: url, Insecure: false}
  162. }
  163. // NewClientWithCredentials returns a new HTTP client that requires authentication.
  164. func NewClientWithCredentials(url, username, password string) *Client {
  165. return &Client{url: url, Insecure: false, username: username, password: password}
  166. }
  167. // NewClientWithAuthorization returns a new client with a custom authorization header.
  168. func NewClientWithAuthorization(url, authorization string) *Client {
  169. return &Client{url: url, Insecure: false, authorizationHeader: authorization}
  170. }
  171. // NewClientWithCacheHeaders returns a new HTTP client that send cache headers.
  172. func NewClientWithCacheHeaders(url, etagHeader, lastModifiedHeader string) *Client {
  173. return &Client{url: url, etagHeader: etagHeader, lastModifiedHeader: lastModifiedHeader, Insecure: false}
  174. }