create a middleware in mux in go

Mux is a powerful HTTP router and dispatcher for Go. It provides a convenient way to handle HTTP requests within your application. Middleware is a piece of software that is invoked before the request handler. It can be used to perform certain operations like authentication, logging, etc., on the incoming HTTP request before it reaches the handler.

Here is an example of how to create a middleware in Mux:

main.go
package main

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gorilla/mux"
)

func main() {
	r := mux.NewRouter()

	// logging middleware
	r.Use(loggingMiddleware)

	// route handler
	r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintln(w, "Hello from the Home Page!")
	})

	// start server
	srv := &http.Server{
		Addr:         ":8080",
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
		Handler:      r,
	}
	srv.ListenAndServe()
}

// logging middleware
func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Printf("Access [%s] %s\n", r.Method, r.URL.String())
		next.ServeHTTP(w, r)
	})
}
721 chars
39 lines

In this example, we define a logging middleware that logs the incoming HTTP method and URL. The logging middleware is added to the router using the Use() method. The middleware is implemented as a function that takes the next http.Handler as a parameter and returns a new http.Handler. The next handler is the handler that is supposed to handle the incoming HTTP request. The logging middleware logs the request and then calls the next.ServeHTTP(w, r) method to pass the request to the next handler in the chain.

Note that the order in which you add the middleware to the router matters. The middleware is executed in the order that it is added. The first middleware that is added to the router is the first to be executed, and the last middleware that is added is the last to be executed.

gistlibby LogSnag