middleware.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package server // import "miniflux.app/v2/internal/http/server"
  4. import (
  5. "context"
  6. "log/slog"
  7. "net/http"
  8. "time"
  9. "miniflux.app/v2/internal/config"
  10. "miniflux.app/v2/internal/http/request"
  11. )
  12. func middleware(next http.Handler) http.Handler {
  13. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  14. clientIP := request.FindClientIP(r)
  15. ctx := r.Context()
  16. ctx = context.WithValue(ctx, request.ClientIPContextKey, clientIP)
  17. if r.Header.Get("X-Forwarded-Proto") == "https" {
  18. config.Opts.SetHTTPSValue(true)
  19. }
  20. t1 := time.Now()
  21. defer func() {
  22. slog.Debug("Incoming request",
  23. slog.String("client_ip", clientIP),
  24. slog.Group("request",
  25. slog.String("method", r.Method),
  26. slog.String("uri", r.RequestURI),
  27. slog.String("protocol", r.Proto),
  28. slog.Duration("execution_time", time.Since(t1)),
  29. ),
  30. )
  31. }()
  32. if config.Opts.HTTPS() && config.Opts.HasHSTS() {
  33. w.Header().Set("Strict-Transport-Security", "max-age=31536000")
  34. }
  35. next.ServeHTTP(w, r.WithContext(ctx))
  36. })
  37. }