proxy.go 1.4 KB

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