Mastering Negroni Middleware in Go: Build and Extend Your HTTP Handlers

This article explains how to create custom middleware for the Go Negroni framework, walks through a complete example with code, and details the internal functions such as UseHandler, Wrap, Use, build, and how Negroni ultimately runs the HTTP server.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Negroni Middleware in Go: Build and Extend Your HTTP Handlers

This article introduces Go language Negroni middleware and shows how to implement custom middleware that can be wrapped and invoked through Negroni.

First, a simple example program is presented:

package main
import (
    "fmt"
    "net/http"
    "github.com/urfave/negroni"
    "github.com/phyber/negroni-gzip/gzip"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "Welcome to the home page!")
    })

    n := negroni.Classic() // create a negroni instance
    n.Use(gzip.Gzip(gzip.DefaultCompression))
    n.UseHandler(mux)
    n.Run(":3000")
}

After creating the Negroni instance, the call n.UseHandler(mux) triggers a chain of internal calls:

n.UseHandler(mux)
    +func (n *Negroni) UseHandler(handler http.Handler)
        |n.Use(Wrap(handler))
        +func Wrap(handler http.Handler) Handler
            |return HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
        +func (n *Negroni) Use(handler Handler)
            |n.handlers = append(n.handlers, handler)
            |n.middleware = build(n.handlers)
            +func build(handlers []Handler) middleware
                |return middleware{handlers[0], &next}

The key functions are:

1. UseHandler

This function forwards the handler to Wrap().

func (n *Negroni) UseHandler(handler http.Handler) {
    n.Use(Wrap(handler))
}

2. Wrap

This function wraps the handler into a fixed‑format Handler implementation.

func Wrap(handler http.Handler) Handler {
    return HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
        handler.ServeHTTP(rw, r)
        next(rw, r)
    })
}

3. Use

This adds the wrapped handler to the Negroni struct, rebuilding the middleware chain.

func (n *Negroni) Use(handler Handler) {
    if handler == nil {
        panic("handler cannot be nil")
    }
    n.handlers = append(n.handlers, handler)
    n.middleware = build(n.handlers)
}

type Negroni struct {
    middleware middleware
    handlers   []Handler
}

type middleware struct {
    handler Handler
    next    *middleware
}

4. build

This recursive function constructs the middleware linked list.

func build(handlers []Handler) middleware {
    var next middleware
    if len(handlers) == 0 {
        return voidMiddleware()
    } else if len(handlers) > 1 {
        next = build(handlers[1:])
    } else {
        next = voidMiddleware()
    }
    return middleware{handlers[0], &next}
}

5. Handler Interface and ServeHTTP

The Handler interface requires a ServeHTTP method. Negroni provides several implementations:

type Handler interface {
    ServeHTTP(ResponseWriter, *Request)
}

type HandlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)

func (h HandlerFunc) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
    h(rw, r, next)
}

func (m middleware) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
    m.handler.ServeHTTP(rw, r, m.next.ServeHTTP)
}

Finally, the call n.Run(":3000") resolves the address and invokes http.ListenAndServe, handing over all registered handlers to the standard Go HTTP server.

Thus, Negroni’s usage of third‑party middleware starts with n.UseHandler, which internally builds a middleware chain that ultimately runs via http.ListenAndServe.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

middlewareGoHTTPNegroni
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.