client.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. "crypto/tls"
  7. "fmt"
  8. "log"
  9. "net/http"
  10. "net/url"
  11. "time"
  12. "github.com/miniflux/miniflux2/helper"
  13. )
  14. const userAgent = "Miniflux <https://miniflux.net/>"
  15. const requestTimeout = 300
  16. // Client is a HTTP Client :)
  17. type Client struct {
  18. url string
  19. etagHeader string
  20. lastModifiedHeader string
  21. Insecure bool
  22. }
  23. // Get execute a GET HTTP request.
  24. func (h *Client) Get() (*Response, error) {
  25. defer helper.ExecutionTime(time.Now(), fmt.Sprintf("[HttpClient:Get] url=%s", h.url))
  26. u, _ := url.Parse(h.url)
  27. req := &http.Request{
  28. URL: u,
  29. Method: "GET",
  30. Header: h.buildHeaders(),
  31. }
  32. client := h.buildClient()
  33. resp, err := client.Do(req)
  34. if err != nil {
  35. return nil, err
  36. }
  37. response := &Response{
  38. Body: resp.Body,
  39. StatusCode: resp.StatusCode,
  40. EffectiveURL: resp.Request.URL.String(),
  41. LastModified: resp.Header.Get("Last-Modified"),
  42. ETag: resp.Header.Get("ETag"),
  43. ContentType: resp.Header.Get("Content-Type"),
  44. }
  45. log.Println("[HttpClient:Get]",
  46. "OriginalURL:", h.url,
  47. "StatusCode:", response.StatusCode,
  48. "ETag:", response.ETag,
  49. "LastModified:", response.LastModified,
  50. "EffectiveURL:", response.EffectiveURL,
  51. )
  52. return response, err
  53. }
  54. func (h *Client) buildClient() http.Client {
  55. client := http.Client{Timeout: time.Duration(requestTimeout * time.Second)}
  56. if h.Insecure {
  57. client.Transport = &http.Transport{
  58. TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
  59. }
  60. }
  61. return client
  62. }
  63. func (h *Client) buildHeaders() http.Header {
  64. headers := make(http.Header)
  65. headers.Add("User-Agent", userAgent)
  66. if h.etagHeader != "" {
  67. headers.Add("If-None-Match", h.etagHeader)
  68. }
  69. if h.lastModifiedHeader != "" {
  70. headers.Add("If-Modified-Since", h.lastModifiedHeader)
  71. }
  72. return headers
  73. }
  74. // NewClient returns a new HTTP client.
  75. func NewClient(url string) *Client {
  76. return &Client{url: url, Insecure: false}
  77. }
  78. // NewClientWithCacheHeaders returns a new HTTP client that send cache headers.
  79. func NewClientWithCacheHeaders(url, etagHeader, lastModifiedHeader string) *Client {
  80. return &Client{url: url, etagHeader: etagHeader, lastModifiedHeader: lastModifiedHeader, Insecure: false}
  81. }