4
0

proxy.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. "io/ioutil"
  9. "net/http"
  10. "time"
  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. // ImageProxy fetch an image from a remote server and sent it back to the browser.
  18. func (c *Controller) 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. clt := client.New(string(decodedURL))
  35. resp, err := clt.Get()
  36. if err != nil {
  37. html.ServerError(w, r, err)
  38. return
  39. }
  40. if resp.HasServerFailure() {
  41. html.NotFound(w, r)
  42. return
  43. }
  44. body, _ := ioutil.ReadAll(resp.Body)
  45. etag := crypto.HashFromBytes(body)
  46. response.New(w ,r).WithCaching(etag, 72*time.Hour, func(b *response.Builder) {
  47. b.WithHeader("Content-Type", resp.ContentType)
  48. b.WithBody(body)
  49. b.WithoutCompression()
  50. b.Write()
  51. })
  52. }