client.go 6.9 KB

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