negroni

repository·master·Indexed 27 days ago

https://github.com/urfave/negroni

A lightweight, idiomatic middleware library for Go that works directly with net/http. It allows developers to bring their own routers and provides a non-intrusive way to manage middleware chains. Key features include a pre-configured Classic stack, Recovery middleware for panic handling, a customizable Logger, and Static file serving. It also provides a ResponseWriter interface to capture response status and size, and supports HTTP/2 server push.

Tokens
10.9K
Snippets
40
Records
69
Agent score
92%

What's inside negroni

  1. Quickstart with negroni.Classic()

    master

    The negroni.Classic() function is a convenient way to start a server with a set of default middleware: Recovery (to handle panics), Logging (to log requests/responses), and Static (to serve files from a "public" directory).

    package main
    
    import (
      "fmt"
      "net/http"
    
      "github.com/urfave/negroni/v3"
    )
    
    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() // Includes default middleware
      n.UseHandler(mux)
    
      http.ListenAndServe(":3000", n)
    }
  2. Quickstart: Create a basic Negroni server

    master

    You can start a basic web server by creating a net/http multiplexer and wrapping it with negroni.Classic(). negroni.Classic() provides default middleware including negroni.Recovery, negroni.Logging, and negroni.Static (for serving files from a public directory).

    package main
    
    import (
      "github.com/urfave/negroni/v3"
      "net/http"
      "fmt"
    )
    
    func main() {
      mux := http.NewServeMux()
      mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "Willkommen auf der Homepage!")
      })
    
      n := negroni.Classic()
      n.UseHandler(mux)
      n.Run(":3000")
    }
  3. Apply route-specific middleware

    master

    To apply middleware to specific routes (e.g., using Gorilla Mux), wrap the sub-router or specific handler in a new Negroni instance. This allows you to isolate middleware to specific path prefixes.

    router := mux.NewRouter()
    apiRoutes := mux.NewRouter()
    
    // Shared middleware base
    common := negroni.New(
    	Middleware1,
    	Middleware2,
    )
    
    // Apply common middleware + API-specific middleware to the /api prefix
    router.PathPrefix("/api").Handler(common.With(
    	APIMiddleware1,
    	negroni.Wrap(apiRoutes),
    ))
  4. Integrate custom routers (BYOR)

    master

    Negroni follows a 'Bring Your Own Router' (BYOR) philosophy. It is designed to work with any net/http compatible router, such as Gorilla Mux. You should add your router as the final handler using UseHandler().

    router := mux.NewRouter()
    router.HandleFunc("/", HomeHandler)
    
    n := negroni.New(Middleware1, Middleware2)
    n.Use(Middleware3)
    // Add the router last
    n.UseHandler(router)
    
    http.ListenAndServe(":3001", n)
  5. Apply middleware to specific routes

    master

    To apply a specific set of middleware to a subset of routes, create a new Negroni instance and wrap it using negroni.Wrap(). You can also use With() to extend a base Negroni instance with additional middleware for specific routes.

    Using negroni.Wrap() with a sub-router:

    router.PathPrefix("/subpath").Handler(negroni.New(
      Middleware1,
      Middleware2,
      negroni.Wrap(subRouter),
    ))

    Using With() to share common middleware:

    common := negroni.New(Middleware1, Middleware2)
    
    // API routes with common middleware + API specific middleware
    router.PathPrefix("/api").Handler(common.With(
      APIMiddleware1,
      negroni.Wrap(apiRoutes),
    ))
  6. Use scaffolding tools for Negroni development

    master

    To speed up the development of Negroni-compatible middleware or full web applications, you can use the following scaffolding tools:

    • mooseware: A skeleton for writing Negroni-compatible middleware handlers.
    • Go-Skeleton: An efficient skeleton for building web-based Go/Negroni projects.
  7. Integrate Negroni with custom routers (TSPR)

    master

    Negroni follows the 'Bring Your Own Routing' (TSPR) pattern. It is designed to work with any net/http compatible router, such as Gorilla Mux. To integrate, add your router as the final handler in the Negroni chain using UseHandler().

    router := mux.NewRouter()
    router.HandleFunc("/", HomeHandler)
    
    n := negroni.New(Middleware1, Middleware2)
    // Or use a middleware with the Use() function
    n.Use(Middleware3)
    // router goes last
    n.UseHandler(router)
    
    n.Run(":3000")
  8. Apply middleware to specific routes (Route Grouping)

    master

    To apply specific middleware to a subset of routes, create a new Negroni instance for that group and wrap it using negroni.Wrap(). This instance can then be passed as a handler to your main router.

    router := mux.NewRouter()
    apiRoutes := mux.NewRouter()
    // add api routes here
    
    // create common middleware to be shared across routes
    common := negroni.New(
    	Middleware1,
    	Middleware2,
    )
    
    // create a new negroni for the api middleware
    // using the common middleware as a base
    router.PathPrefix("/api").Handler(common.With(
      APIMiddleware1,
      negroni.Wrap(apiRoutes),
    ))
  9. Integrate Negroni with a Router

    master

    Negroni is not a router; it is a middleware library. You should use it alongside a router like net/http.ServeMux or gorilla/mux. To integrate, use n.UseHandler(router) to ensure the router is the final handler in the middleware chain.

    router := mux.NewRouter()
    router.HandleFunc("/", HomeHandler)
    
    n := negroni.New(Middleware1, Middleware2)
    // Or use a middleware with the Use() function
    n.Use(Middleware3)
    // router goes last
    n.UseHandler(router)
    
    http.ListenAndServe(":3001", n)
  10. Apply middleware to specific route groups

    master

    To apply middleware to a specific subset of routes, create a new Negroni instance for that group and wrap it using negroni.Wrap(). This instance can then be used as a handler within your main router.

    router := mux.NewRouter()
    adminRoutes := mux.NewRouter()
    // Add Admin routes here
    
    // Create a new Negroni instance for the Admin middleware
    router.Handle("/admin", negroni.New(
      Middleware1,
      Middleware2,
      negroni.Wrap(adminRoutes),
    ))