4
0

middleware.go 1.3 KB

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