handler.go 1.7 KB

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