proxy.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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
  5. import (
  6. "encoding/base64"
  7. "errors"
  8. "io/ioutil"
  9. "net/http"
  10. "time"
  11. "github.com/miniflux/miniflux/crypto"
  12. "github.com/miniflux/miniflux/http/client"
  13. "github.com/miniflux/miniflux/http/request"
  14. "github.com/miniflux/miniflux/http/response"
  15. "github.com/miniflux/miniflux/http/response/html"
  16. "github.com/miniflux/miniflux/logger"
  17. )
  18. // ImageProxy fetch an image from a remote server and sent it back to the browser.
  19. func (c *Controller) ImageProxy(w http.ResponseWriter, r *http.Request) {
  20. // If we receive a "If-None-Match" header we assume the image in stored in browser cache
  21. if r.Header.Get("If-None-Match") != "" {
  22. response.NotModified(w)
  23. return
  24. }
  25. encodedURL := request.Param(r, "encodedURL", "")
  26. if encodedURL == "" {
  27. html.BadRequest(w, errors.New("No URL provided"))
  28. return
  29. }
  30. decodedURL, err := base64.URLEncoding.DecodeString(encodedURL)
  31. if err != nil {
  32. html.BadRequest(w, errors.New("Unable to decode this URL"))
  33. return
  34. }
  35. clt := client.New(string(decodedURL))
  36. resp, err := clt.Get()
  37. if err != nil {
  38. logger.Error("[Controller:ImageProxy] %v", err)
  39. html.NotFound(w)
  40. return
  41. }
  42. if resp.HasServerFailure() {
  43. html.NotFound(w)
  44. return
  45. }
  46. body, _ := ioutil.ReadAll(resp.Body)
  47. etag := crypto.HashFromBytes(body)
  48. response.Cache(w, r, resp.ContentType, etag, body, 72*time.Hour)
  49. }