proxy.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. "miniflux.app/logger"
  17. )
  18. func (h *handler) imageProxy(w http.ResponseWriter, r *http.Request) {
  19. // If we receive a "If-None-Match" header, we assume the image is already stored in browser cache.
  20. if r.Header.Get("If-None-Match") != "" {
  21. w.WriteHeader(http.StatusNotModified)
  22. return
  23. }
  24. encodedURL := request.RouteStringParam(r, "encodedURL")
  25. if encodedURL == "" {
  26. html.BadRequest(w, r, errors.New("No URL provided"))
  27. return
  28. }
  29. decodedURL, err := base64.URLEncoding.DecodeString(encodedURL)
  30. if err != nil {
  31. html.BadRequest(w, r, errors.New("Unable to decode this URL"))
  32. return
  33. }
  34. imageURL := string(decodedURL)
  35. logger.Debug(`[Proxy] Fetching %q`, imageURL)
  36. req, err := http.NewRequest("GET", imageURL, nil)
  37. if err != nil {
  38. html.ServerError(w, r, err)
  39. return
  40. }
  41. req.Header.Add("User-Agent", client.DefaultUserAgent)
  42. req.Header.Add("Connection", "close")
  43. clt := &http.Client{
  44. Timeout: time.Duration(config.Opts.HTTPClientTimeout()) * time.Second,
  45. }
  46. resp, err := clt.Do(req)
  47. if err != nil {
  48. html.ServerError(w, r, err)
  49. return
  50. }
  51. defer resp.Body.Close()
  52. if resp.StatusCode != http.StatusOK {
  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-Type", resp.Header.Get("Content-Type"))
  59. b.WithBody(resp.Body)
  60. b.WithoutCompression()
  61. b.Write()
  62. })
  63. }