gin middleware example
The Go language provides a middleware package for building web applications. Middleware functions are used to process HTTP requests and responses before and after they reach the main handler function. Here is an example of how to use middleware in Go:
Step 1: Import the necessary packages
import (
"net/http"
"fmt"
)
Step 2: Define your middleware function
func myMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Code to be executed before reaching the main handler
fmt.Println("Executing middleware...")
// Call the next middleware/handler in the chain
next.ServeHTTP(w, r)
// Code to be executed after reaching the main handler
fmt.Println("Middleware execution completed.")
})
}
Step 3: Create your main handler function
func mainHandler(w http.ResponseWriter, r *http.Request) {
// Code to handle the request
fmt.Println("Handling request...")
// Write response back to client
w.Write([]byte("Hello, World!"))
}
Step 4: Use the middleware in your application
func main() {
// Create a new router instance
router := http.NewServeMux()
// Use the middleware with your main handler
router.Handle("/", myMiddleware(http.HandlerFunc(mainHandler)))
// Start the server
http.ListenAndServe(":8080", router)
}
In this example, the myMiddleware
function is defined to log a message before and after the main handler is executed. The next
parameter is a reference to the next middleware or handler in the chain, allowing the request to be processed further.
By using the router.Handle
function, we apply the middleware to the root path ("/") of our application. This ensures that the middleware is executed for every request that matches the specified path.
When the server is started with http.ListenAndServe
, the middleware will be executed before the main handler for each incoming request.
That's it! This example demonstrates the basic usage of middleware in Go. You can add more middleware functions to the chain by wrapping them around the next
parameter in the myMiddleware
function.