CodexBloom - Programming Q&A Platform

Difficulty with Go's HTTP Server Handling Redirects When Using net/http with Custom Middleware

šŸ‘€ Views: 1331 šŸ’¬ Answers: 1 šŸ“… Created: 2025-08-22
go http middleware logging Go

I've been working on this all day and I've tried everything I can think of but I've searched everywhere and can't find a clear answer. I'm having trouble with my Go HTTP server where it seems to not properly handle HTTP redirects when using a custom middleware for logging. I set up a basic server using Go's `net/http` package and implemented a middleware to log incoming requests. However, when a client makes a request that gets redirected (like from HTTP to HTTPS), the middleware is not logging the redirect as expected, which leads to missing logs and confusion about user behavior. Here's a simplified version of my code: ```go package main import ( "fmt" "net/http" ) // Logging middleware logs the request method and URL func loggingMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Printf("%s %s\n", r.Method, r.URL) next.ServeHTTP(w, r) }) } func helloHandler(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, world!") } func main() { mux := http.NewServeMux() mux.HandleFunc("/hello", helloHandler) // Force HTTP to HTTPS redirect go func() { http.ListenAndServe(":8080", mux) }() // Start HTTPS server http.ListenAndServeTLS(":8443", "server.crt", "server.key", loggingMiddleware(mux)) } ``` In this setup, I have a basic HTTP server listening on port 8080 and an HTTPS server on port 8443 using `ListenAndServeTLS`. When I access the HTTP endpoint, it correctly redirects to HTTPS, but I don't see any logs from the middleware for that redirect in the console. I've tried adding logging before the `next.ServeHTTP(w, r)` call, but it still doesn't catch the redirect. I verified that the client is indeed following the redirect by checking the network tab, but it's like the middleware doesn't get invoked for the redirect response. Is there a way to ensure that the redirect is logged properly and that my middleware handles such cases? I’m using Go version 1.19.1. For context: I'm using Go on Ubuntu. Any ideas what could be causing this? This is for a microservice running on Linux. Cheers for any assistance! What am I doing wrong? This is part of a larger service I'm building. What's the best practice here?