4
0

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