Home

Creating and Implementing Middleware in a Go Web Server with Net/HTTP Package

24 views

"Certainly! In Go, middleware is typically implemented as a function that wraps the http.Handler. Below is an example of how you can create and use middleware in a Go web server using the net/http package.

  1. Install Go: Ensure you have Go installed and set up on your system.

  2. Create a basic server with middleware:

package main

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

// Middleware function
func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        start := time.Now()
        log.Printf("Request: %s %s", r.Method, r.URL.Path)
        next.ServeHTTP(w, r) // Call the next handler
        log.Printf("Completed in %s", time.Since(start))
    })
}

// Example handler
func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintln(w, "Hello World!")
}

// Another example handler
func aboutHandler(w http.ResponseWriter, r *Request) {
    fmt.Fprintln(w, "About Page")
}

func main() {
    mux := http.NewServeMux()

    // Define routes
    mux.Handle("/", loggingMiddleware(http.HandlerFunc(helloHandler)))
    mux.Handle("/about", loggingMiddleware(http.HandlerFunc(aboutHandler)))

    // Start the server
    port := ":3000"
    fmt.Printf("Server is running on http://localhost%s\n", port)
    err := http.ListenAndServe(port, mux)
    if err != nil {
        log.Fatalf("Server failed: %s", err)
    }
}

Explanation:

  1. Package Declaration:

    package main
    
  2. Imports: Import necessary packages like fmt, log, net/http, and time.

  3. Middleware Function (loggingMiddleware):

    • This middleware logs the HTTP request method and the request URL.
    • The loggingMiddleware function takes an http.Handler as an argument and returns an http.Handler.
    • Inside the middleware, http.HandlerFunc is used to create a function that wraps the logic for logging the request details and calling the next handler.
  4. Example Handlers:

    • helloHandler responds with "Hello World!".
    • aboutHandler responds with "About Page".
  5. Main Function:

    • Create a new http.ServeMux to handle incoming requests.
    • Define routes using mux.Handle and wrap the handlers with the loggingMiddleware.
    • Start the server with http.ListenAndServe on port 3000.

To run this server, save the code in a file (e.g., main.go), and execute it using the Go command:

go run main.go

You'll see output like:

Server is running on http://localhost:3000

When you make requests to http://localhost:3000/ or http://localhost:3000/about, you'll see the corresponding messages in the web browser, and logged request information in the console:

Request: GET /
Completed in 203.583µs
Request: GET /about
Completed in 110.745µs

This demonstrates a basic implementation of middleware in a Go web server using the net/http package. For more detailed examples on iterating over maps in Go, you can refer to this post."