go-sdk/examples/http/logging_middleware.go
Adam Koszek a617dcea31
mcp/examples: HTTP server example with a simple client built-in (#168)
I'm adding a practical example of an MCP with HTTP streaming: both
client and server. Those are useful for testing real-world applications.
2025-08-30 14:30:48 -04:00

51 lines
1.2 KiB
Go

// Copyright 2025 The Go MCP SDK Authors. All rights reserved.
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package main
import (
"log"
"net/http"
"time"
)
// responseWriter wraps http.ResponseWriter to capture the status code.
type responseWriter struct {
http.ResponseWriter
statusCode int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
func loggingHandler(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Create a response writer wrapper to capture status code.
wrapped := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
// Log request details.
log.Printf("[REQUEST] %s | %s | %s %s",
start.Format(time.RFC3339),
r.RemoteAddr,
r.Method,
r.URL.Path)
// Call the actual handler.
handler.ServeHTTP(wrapped, r)
// Log response details.
duration := time.Since(start)
log.Printf("[RESPONSE] %s | %s | %s %s | Status: %d | Duration: %v",
time.Now().Format(time.RFC3339),
r.RemoteAddr,
r.Method,
r.URL.Path,
wrapped.statusCode,
duration)
})
}