handler.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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 core
  5. import (
  6. "net/http"
  7. "time"
  8. "github.com/miniflux/miniflux/config"
  9. "github.com/miniflux/miniflux/locale"
  10. "github.com/miniflux/miniflux/logger"
  11. "github.com/miniflux/miniflux/server/middleware"
  12. "github.com/miniflux/miniflux/server/template"
  13. "github.com/miniflux/miniflux/storage"
  14. "github.com/miniflux/miniflux/timer"
  15. "github.com/gorilla/mux"
  16. "github.com/tomasen/realip"
  17. )
  18. // HandlerFunc is an application HTTP handler.
  19. type HandlerFunc func(ctx *Context, request *Request, response *Response)
  20. // Handler manages HTTP handlers and middlewares.
  21. type Handler struct {
  22. cfg *config.Config
  23. store *storage.Storage
  24. translator *locale.Translator
  25. template *template.Engine
  26. router *mux.Router
  27. middleware *middleware.Chain
  28. }
  29. // Use is a wrapper around an HTTP handler.
  30. func (h *Handler) Use(f HandlerFunc) http.Handler {
  31. return h.middleware.WrapFunc(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  32. defer timer.ExecutionTime(time.Now(), r.URL.Path)
  33. logger.Debug("[HTTP] %s %s %s", realip.RealIP(r), r.Method, r.URL.Path)
  34. if r.Header.Get("X-Forwarded-Proto") == "https" {
  35. h.cfg.IsHTTPS = true
  36. }
  37. ctx := NewContext(w, r, h.store, h.router, h.translator)
  38. request := NewRequest(w, r)
  39. response := NewResponse(w, r, h.template)
  40. if ctx.IsAuthenticated() {
  41. h.template.SetLanguage(ctx.UserLanguage())
  42. } else {
  43. h.template.SetLanguage("en_US")
  44. }
  45. f(ctx, request, response)
  46. }))
  47. }
  48. // NewHandler returns a new Handler.
  49. func NewHandler(cfg *config.Config, store *storage.Storage, router *mux.Router, template *template.Engine, translator *locale.Translator, middleware *middleware.Chain) *Handler {
  50. return &Handler{
  51. cfg: cfg,
  52. store: store,
  53. translator: translator,
  54. router: router,
  55. template: template,
  56. middleware: middleware,
  57. }
  58. }