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.
This commit is contained in:
parent
7bfde44981
commit
a617dcea31
1 changed files with 320 additions and 0 deletions
51
examples/http/logging_middleware.go
Normal file
51
examples/http/logging_middleware.go
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
// 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)
|
||||
})
|
||||
}
|
||||
Loading…
Reference in a new issue