View : 0

12/04/2026 18:16pm

Ep.21  Go and HTTP Middleware: Mastering Request Control!

Ep.21 Go and HTTP Middleware: Mastering Request Control!

#Go

#Golang

#Go language

#HTTP

#Middleware

#request management

#authentication

#Logging

#web development

#Go Programming

#Programming Education

#Practice programming

#programming language

#programming for beginners

#programming

#programmers

#Superdev School

Go and HTTP Middleware: Mastering Request Control!

 

What is Middleware?

Middleware is a component that manages requests or responses before they reach our main handler. This can include tasks such as authentication, logging, or header management.
Example of Middleware Functionality :

  • Receives a request from the user
  • Checks or modifies the request (e.g., verifying a token)
  • Forwards it to the main handler
  • After the handler processes the request, the middleware may modify the response before sending it back to the user.

 

Creating Simple Middleware in Go Example of Middleware Creation

In this example, the loggingMiddleware logs every incoming request.
The middleware operates before the helloHandler.

package main

import (
    "fmt"
    "net/http"
)

func loggingMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        fmt.Printf("Request: %s %s\n", r.Method, r.URL.Path)
        next.ServeHTTP(w, r) // ส่ง Request ไปยัง Handler ถัดไป
    })
}

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

func main() {
    mux := http.NewServeMux()
    mux.Handle("/", loggingMiddleware(http.HandlerFunc(helloHandler)))

    fmt.Println("Server started at :8080")
    http.ListenAndServe(":8080", mux)
}

 

Authentication Middleware

Middleware can be used to verify a token to confirm whether a user has access rights.
In this example, the authMiddleware checks for the presence of an Authorization header and whether it has the value of "valid-token."

If not, it will return an "Unauthorized" message with a 401 status.

func authMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        token := r.Header.Get("Authorization")
        if token != "valid-token" {
            http.Error(w, "Unauthorized", http.StatusUnauthorized)
            return
        }
        next.ServeHTTP(w, r) // ส่งต่อไปยัง Handler ถ้าสิทธิ์ถูกต้อง
    })
}

func main() {
    mux := http.NewServeMux()
    mux.Handle("/", authMiddleware(http.HandlerFunc(helloHandler)))

    fmt.Println("Server started at :8080")
    http.ListenAndServe(":8080", mux)
}

 

Chaining Multiple Middleware

We can chain multiple middleware together to enhance request and response control.
Example of Multiple Middleware :

In this example, we use chainMiddleware to connect several middleware components, arranging their execution from top to bottom.

func chainMiddleware(h http.Handler, middlewares ...func(http.Handler) http.Handler) http.Handler {
    for _, middleware := range middlewares {
        h = middleware(h)
    }
    return h
}

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

    mux.Handle("/", chainMiddleware(
        http.HandlerFunc(helloHandler),
        loggingMiddleware,
        authMiddleware,
    ))

    fmt.Println("Server started at :8080")
    http.ListenAndServe(":8080", mux)
}

 

Common Use Cases for Middleware

  • Authentication
  • Logging
  • Managing CORS (Cross-Origin Resource Sharing)
  • Data Compression
  • Error Handling

 

In Summary

  • Middleware helps manage requests/responses before and after they reach the main handler.
  • Multiple middleware can be used together (chaining) to handle various steps.
  • Middleware is ideal for repetitive tasks such as authentication and logging.