trying embedded caddy reverse proxy

This commit is contained in:
pascal
2026-01-14 17:16:42 +01:00
parent d9118eb239
commit 626e892e3b
30 changed files with 6978 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
package middleware
import "net/http"
// Chain creates a middleware chain
func Chain(handler http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler {
// Apply middlewares in reverse order so they execute in the order provided
for i := len(middlewares) - 1; i >= 0; i-- {
handler = middlewares[i](handler)
}
return handler
}
+55
View File
@@ -0,0 +1,55 @@
package middleware
import (
"net/http"
"time"
log "github.com/sirupsen/logrus"
)
// responseWriter wraps http.ResponseWriter to capture status code
type responseWriter struct {
http.ResponseWriter
statusCode int
written int64
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
func (rw *responseWriter) Write(b []byte) (int, error) {
n, err := rw.ResponseWriter.Write(b)
rw.written += int64(n)
return n, err
}
// Logging middleware logs HTTP requests with details
func Logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Wrap the response writer
wrapped := &responseWriter{
ResponseWriter: w,
statusCode: http.StatusOK,
}
// Call the next handler
next.ServeHTTP(wrapped, r)
// Log request details
duration := time.Since(start)
log.WithFields(log.Fields{
"method": r.Method,
"path": r.URL.Path,
"status": wrapped.statusCode,
"duration_ms": duration.Milliseconds(),
"bytes": wrapped.written,
"remote_addr": r.RemoteAddr,
"user_agent": r.UserAgent(),
}).Info("HTTP request")
})
}
+33
View File
@@ -0,0 +1,33 @@
package middleware
import (
"fmt"
"net/http"
"runtime/debug"
log "github.com/sirupsen/logrus"
)
// Recovery middleware recovers from panics and logs the error
func Recovery(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
// Log the panic with stack trace
log.WithFields(log.Fields{
"error": err,
"method": r.Method,
"path": r.URL.Path,
"stack": string(debug.Stack()),
"remote_addr": r.RemoteAddr,
}).Error("Panic recovered")
// Return 500 Internal Server Error
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Internal Server Error")
}
}()
next.ServeHTTP(w, r)
})
}