middleware.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. remoteIP := request.FindRemoteIP(r)
  15. trustedNetworks := config.Opts.TrustedReverseProxyNetworks()
  16. isTrustedProxyClientIP := request.IsTrustedIP(remoteIP, trustedNetworks)
  17. clientIP := request.FindClientIP(r, isTrustedProxyClientIP, trustedNetworks)
  18. ctx := r.Context()
  19. ctx = context.WithValue(ctx, request.ClientIPContextKey, clientIP)
  20. if isTrustedProxyClientIP && r.Header.Get("X-Forwarded-Proto") == "https" {
  21. config.Opts.SetHTTPSValue(true)
  22. }
  23. t1 := time.Now()
  24. defer func() {
  25. slog.Debug("Incoming request",
  26. slog.String("client_ip", clientIP),
  27. slog.Group("request",
  28. slog.String("method", r.Method),
  29. slog.String("uri", r.RequestURI),
  30. slog.String("protocol", r.Proto),
  31. slog.Duration("execution_time", time.Since(t1)),
  32. ),
  33. )
  34. }()
  35. if config.Opts.HTTPS() && config.Opts.HasHSTS() {
  36. w.Header().Set("Strict-Transport-Security", "max-age=31536000")
  37. }
  38. next.ServeHTTP(w, r.WithContext(ctx))
  39. })
  40. }