Mahakam supports middlewares. the middlewares actually are just a function that takes a http.Handler
as input and returns a http.Handler
.
type Middleware = func(http.HandlerFunc) http.HandlerFunc
Example
Here is an example of a middleware that logs the request method and path.
func Logger(next http.HandlerFunc) http.HandlerFunc {
logger := slog.Default()
return func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next(w, r)
duration := time.Since(start)
logger.Info("HTTP Request",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("query", r.URL.RawQuery),
slog.String("remote_addr", r.RemoteAddr),
slog.Duration("duration", duration),
slog.String("protocol", r.Proto),
)
}
}
and here is how to use it in your handler.
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, World!"))
})
s := mahakam.NewServer("localhost:8080", mux)
s.Use(middleware.Logger)
if err := s.ListenAndServe(); err != nil {
log.Fatalln("Failed to start server:", err)
}
}
Built-in middlewares
Mahakam provides some built-in middlewares that you can use in your project.
ℹ️ Info
The middleware are still in development. I’m still working on them.
middleware.Logger
This middleware logs the request method, path, query, remote address, duration, and protocol. It uses the slog package for logging.
middleware.Recover
This middleware recovers from panics and logs the error.