client.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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. "encoding/json"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "time"
  15. "github.com/miniflux/miniflux/helper"
  16. "github.com/miniflux/miniflux/logger"
  17. )
  18. // Note: Some websites have a user agent filter.
  19. const userAgent = "Mozilla/5.0 (like Gecko, like Safari, like Chrome) - Miniflux <https://miniflux.net/>"
  20. const requestTimeout = 300
  21. // Client is a HTTP Client :)
  22. type Client struct {
  23. url string
  24. etagHeader string
  25. lastModifiedHeader string
  26. authorizationHeader string
  27. username string
  28. password string
  29. Insecure bool
  30. }
  31. // Get execute a GET HTTP request.
  32. func (c *Client) Get() (*Response, error) {
  33. request, err := c.buildRequest(http.MethodGet, nil)
  34. if err != nil {
  35. return nil, err
  36. }
  37. return c.executeRequest(request)
  38. }
  39. // PostForm execute a POST HTTP request with form values.
  40. func (c *Client) PostForm(values url.Values) (*Response, error) {
  41. request, err := c.buildRequest(http.MethodPost, strings.NewReader(values.Encode()))
  42. if err != nil {
  43. return nil, err
  44. }
  45. request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  46. return c.executeRequest(request)
  47. }
  48. // PostJSON execute a POST HTTP request with JSON payload.
  49. func (c *Client) PostJSON(data interface{}) (*Response, error) {
  50. b, err := json.Marshal(data)
  51. if err != nil {
  52. return nil, err
  53. }
  54. request, err := c.buildRequest(http.MethodPost, bytes.NewReader(b))
  55. if err != nil {
  56. return nil, err
  57. }
  58. request.Header.Add("Content-Type", "application/json")
  59. return c.executeRequest(request)
  60. }
  61. func (c *Client) executeRequest(request *http.Request) (*Response, error) {
  62. defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[HttpClient] url=%s", c.url))
  63. client := c.buildClient()
  64. resp, err := client.Do(request)
  65. if err != nil {
  66. return nil, err
  67. }
  68. response := &Response{
  69. Body: resp.Body,
  70. StatusCode: resp.StatusCode,
  71. EffectiveURL: resp.Request.URL.String(),
  72. LastModified: resp.Header.Get("Last-Modified"),
  73. ETag: resp.Header.Get("ETag"),
  74. ContentType: resp.Header.Get("Content-Type"),
  75. }
  76. logger.Debug("[HttpClient:%s] OriginalURL=%s, StatusCode=%d, ETag=%s, LastModified=%s, EffectiveURL=%s",
  77. request.Method,
  78. c.url,
  79. response.StatusCode,
  80. response.ETag,
  81. response.LastModified,
  82. response.EffectiveURL,
  83. )
  84. return response, err
  85. }
  86. func (c *Client) buildRequest(method string, body io.Reader) (*http.Request, error) {
  87. request, err := http.NewRequest(method, c.url, body)
  88. if err != nil {
  89. return nil, err
  90. }
  91. if c.username != "" && c.password != "" {
  92. request.SetBasicAuth(c.username, c.password)
  93. }
  94. request.Header = c.buildHeaders()
  95. return request, nil
  96. }
  97. func (c *Client) buildClient() http.Client {
  98. client := http.Client{Timeout: time.Duration(requestTimeout * time.Second)}
  99. if c.Insecure {
  100. client.Transport = &http.Transport{
  101. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  102. }
  103. }
  104. return client
  105. }
  106. func (c *Client) buildHeaders() http.Header {
  107. headers := make(http.Header)
  108. headers.Add("User-Agent", userAgent)
  109. headers.Add("Accept", "*/*")
  110. if c.etagHeader != "" {
  111. headers.Add("If-None-Match", c.etagHeader)
  112. }
  113. if c.lastModifiedHeader != "" {
  114. headers.Add("If-Modified-Since", c.lastModifiedHeader)
  115. }
  116. if c.authorizationHeader != "" {
  117. headers.Add("Authorization", c.authorizationHeader)
  118. }
  119. return headers
  120. }
  121. // NewClient returns a new HTTP client.
  122. func NewClient(url string) *Client {
  123. return &Client{url: url, Insecure: false}
  124. }
  125. // NewClientWithCredentials returns a new HTTP client that requires authentication.
  126. func NewClientWithCredentials(url, username, password string) *Client {
  127. return &Client{url: url, Insecure: false, username: username, password: password}
  128. }
  129. // NewClientWithAuthorization returns a new client with a custom authorization header.
  130. func NewClientWithAuthorization(url, authorization string) *Client {
  131. return &Client{url: url, Insecure: false, authorizationHeader: authorization}
  132. }
  133. // NewClientWithCacheHeaders returns a new HTTP client that send cache headers.
  134. func NewClientWithCacheHeaders(url, etagHeader, lastModifiedHeader string) *Client {
  135. return &Client{url: url, etagHeader: etagHeader, lastModifiedHeader: lastModifiedHeader, Insecure: false}
  136. }