proxy.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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/client"
  13. "miniflux.app/http/request"
  14. "miniflux.app/http/response"
  15. "miniflux.app/http/response/html"
  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. req, err := http.NewRequest("GET", string(decodedURL), nil)
  34. if err != nil {
  35. html.ServerError(w, r, err)
  36. return
  37. }
  38. req.Header.Add("User-Agent", client.DefaultUserAgent)
  39. req.Header.Add("Connection", "close")
  40. clt := &http.Client{
  41. Timeout: time.Duration(config.Opts.HTTPClientTimeout()) * time.Second,
  42. }
  43. resp, err := clt.Do(req)
  44. if err != nil {
  45. html.ServerError(w, r, err)
  46. return
  47. }
  48. defer resp.Body.Close()
  49. if resp.StatusCode != http.StatusOK {
  50. html.NotFound(w, r)
  51. return
  52. }
  53. etag := crypto.HashFromBytes(decodedURL)
  54. response.New(w, r).WithCaching(etag, 72*time.Hour, func(b *response.Builder) {
  55. b.WithHeader("Content-Type", resp.Header.Get("Content-Type"))
  56. b.WithBody(resp.Body)
  57. b.WithoutCompression()
  58. b.Write()
  59. })
  60. }