How to create and use middleware in a Go web application?

To create and use middleware in a Go web application, you can follow these steps:

  1. Import the required packages:
import ( "net/http" "log" )
  1. Define a middleware function:
func middleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Code for middleware logic goes here log.Println("Executing middleware") // Call the next handler next.ServeHTTP(w, r) }) }
  1. Create a handler function that will be executed after the middleware:
func handler(w http.ResponseWriter, r *http.Request) { // Code for handling the request goes here log.Println("Executing handler") }
  1. Create a new ServeMux and register the middleware and handler functions:
func main() { mux := http.NewServeMux() // Use the middleware for all requests mux.Handle("/", middleware(http.HandlerFunc(handler))) // Start the server log.Println("Starting server on port 8080") http.ListenAndServe(":8080", mux) }
  1. Run the application and visit http://localhost:8080 to see the logs for the middleware and handler functions.

Note: The middleware function can be used for any custom logic that needs to be executed before or after handling a request, such as authentication, logging, error handling, etc. You can add additional middleware functions by chaining them in the ServeMux registration.