4
0

proxy.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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 ui // import "miniflux.app/ui"
  5. import (
  6. "encoding/base64"
  7. "errors"
  8. "net/http"
  9. "time"
  10. "miniflux.app/config"
  11. "miniflux.app/crypto"
  12. "miniflux.app/http/request"
  13. "miniflux.app/http/response"
  14. "miniflux.app/http/response/html"
  15. "miniflux.app/logger"
  16. )
  17. func (h *handler) imageProxy(w http.ResponseWriter, r *http.Request) {
  18. // If we receive a "If-None-Match" header, we assume the image is already stored in browser cache.
  19. if r.Header.Get("If-None-Match") != "" {
  20. w.WriteHeader(http.StatusNotModified)
  21. return
  22. }
  23. encodedURL := request.RouteStringParam(r, "encodedURL")
  24. if encodedURL == "" {
  25. html.BadRequest(w, r, errors.New("No URL provided"))
  26. return
  27. }
  28. decodedURL, err := base64.URLEncoding.DecodeString(encodedURL)
  29. if err != nil {
  30. html.BadRequest(w, r, errors.New("Unable to decode this URL"))
  31. return
  32. }
  33. imageURL := string(decodedURL)
  34. logger.Debug(`[Proxy] Fetching %q`, imageURL)
  35. req, err := http.NewRequest("GET", imageURL, nil)
  36. if err != nil {
  37. html.ServerError(w, r, err)
  38. return
  39. }
  40. // Note: User-Agent HTTP header is omitted to avoid being blocked by bot protection mechanisms.
  41. req.Header.Add("Connection", "close")
  42. clt := &http.Client{
  43. Timeout: time.Duration(config.Opts.HTTPClientTimeout()) * time.Second,
  44. }
  45. resp, err := clt.Do(req)
  46. if err != nil {
  47. html.ServerError(w, r, err)
  48. return
  49. }
  50. defer resp.Body.Close()
  51. if resp.StatusCode != http.StatusOK {
  52. logger.Error(`[Proxy] Status Code is %d for URL %q`, resp.StatusCode, imageURL)
  53. html.NotFound(w, r)
  54. return
  55. }
  56. etag := crypto.HashFromBytes(decodedURL)
  57. response.New(w, r).WithCaching(etag, 72*time.Hour, func(b *response.Builder) {
  58. b.WithHeader("Content-Security-Policy", `default-src 'self'`)
  59. b.WithHeader("Content-Type", resp.Header.Get("Content-Type"))
  60. b.WithBody(resp.Body)
  61. b.WithoutCompression()
  62. b.Write()
  63. })
  64. }