### Basic Server Setup with Negroni Source: https://github.com/urfave/negroni/blob/master/README.md This snippet demonstrates how to set up a basic web server using Negroni's Classic middleware. It includes a simple HTTP handler for the root path and starts the server on port 3000. Ensure Negroni is installed using 'go get'. ```go 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 some default middlewares n.UseHandler(mux) http.ListenAndServe(":3000", n) } ``` -------------------------------- ### Integrate Negroni with net/http Server Source: https://github.com/urfave/negroni/blob/master/README.md This example shows how to use Negroni as a handler within a standard `http.Server`. It's more flexible than `Run` and allows for custom server configurations. ```go package main import ( "fmt" "log" "net/http" "time" "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 some default middlewares n.UseHandler(mux) s := &http.Server{ Addr: ":8080", Handler: n, ReadTimeout: 10 * time.Second, WriteTimeout: 10 * time.Second, MaxHeaderBytes: 1 << 20, } log.Fatal(s.ListenAndServe()) } ``` -------------------------------- ### Install Negroni Package Source: https://github.com/urfave/negroni/blob/master/README.md Command to install the Negroni package for Go projects. Requires Go version 1.1 or later. ```bash go get github.com/urfave/negroni/v3 ``` -------------------------------- ### Run Negroni Server with Classic Middleware Source: https://github.com/urfave/negroni/blob/master/README.md Use the `Run` function for a quick way to start a Negroni server with classic middleware. It accepts an address string similar to `http.ListenAndServe`. ```go package main import ( "github.com/urfave/negroni/v3" ) func main() { n := negroni.Classic() n.Run(":8080") } ``` -------------------------------- ### Serve Static Files with Negroni Source: https://github.com/urfave/negroni/blob/master/README.md This example demonstrates using Negroni's `NewStatic` middleware to serve files from the filesystem. If a file is not found, it proxies the request to the next handler. ```go 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!") }) // Example of using a http.FileServer if you want "server-like" rather than "middleware" behavior // mux.Handle("/public", http.FileServer(http.Dir("/home/public"))) n := negroni.New() n.Use(negroni.NewStatic(http.Dir("/tmp"))) n.UseHandler(mux) http.ListenAndServe(":3002", n) } ``` -------------------------------- ### Integrate Negroni with Gorilla Mux Router Source: https://github.com/urfave/negroni/blob/master/README.md Example of integrating Negroni with the Gorilla Mux router. It shows how to create a router, define routes, and then use Negroni's `UseHandler` to attach the router as the last handler in the chain. ```go 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) ``` -------------------------------- ### Custom Middleware Function Example Source: https://github.com/urfave/negroni/blob/master/README.md Defines a custom middleware function that can be added to the Negroni chain. The function executes logic before and after calling the next handler in the chain. ```go func MyMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { // do some stuff before next(rw, r) // do some stuff after } ``` -------------------------------- ### Route Specific Middleware with Gorilla Mux Subrouter Source: https://github.com/urfave/negroni/blob/master/README.md Example using Negroni with Gorilla Mux's subrouters to apply middleware to specific path prefixes. Ensure the subrouter is correctly linked to the main router. ```go router := mux.NewRouter() subRouter := mux.NewRouter().PathPrefix("/subpath").Subrouter().StrictSlash(true) subRouter.HandleFunc("/", someSubpathHandler) // "/subpath/" subRouter.HandleFunc("/:id", someSubpathHandler) // "/subpath/:id" // "/subpath" is necessary to ensure the subRouter and main router linkup router.PathPrefix("/subpath").Handler(negroni.New( Middleware1, Middleware2, negroni.Wrap(subRouter), )) ``` -------------------------------- ### Combine Middleware with Negroni.With() Source: https://github.com/urfave/negroni/blob/master/README.md Illustrates using the `With()` function to create a new Negroni instance that inherits handlers from a base instance and adds new ones. This is useful for reusing common middleware configurations. ```go // middleware we want to reuse common := negroni.New() common.Use(MyMiddleware1) common.Use(MyMiddleware2) // `specific` is a new negroni with the handlers from `common` combined with the // the handlers passed in specific := common.With( SpecificMiddleware1, SpecificMiddleware2 ) ``` -------------------------------- ### Shared Middleware with Negroni's With() Source: https://github.com/urfave/negroni/blob/master/README.md Use the `With()` method to create new Negroni instances that inherit common middleware, reducing redundancy when applying shared middleware to different route groups. ```go router := mux.NewRouter() apiRoutes := mux.NewRouter() // add api routes here webRoutes := mux.NewRouter() // add web 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), )) // create a new negroni for the web middleware // using the common middleware as a base router.PathPrefix("/web").Handler(common.With( WebMiddleware1, negroni.Wrap(webRoutes), )) ``` -------------------------------- ### Add Custom Middleware using HandlerFunc Source: https://github.com/urfave/negroni/blob/master/README.md Demonstrates how to add a custom middleware function to a Negroni instance by wrapping it with `negroni.HandlerFunc`. ```go n := negroni.New() n.Use(negroni.HandlerFunc(MyMiddleware)) ``` -------------------------------- ### Map HTTP Handlers to Negroni Source: https://github.com/urfave/negroni/blob/master/README.md Shows how to integrate standard Go `http.Handler`s, such as those created with `http.NewServeMux`, into a Negroni chain using `UseHandler`. ```go n := negroni.New() mux := http.NewServeMux() // map your routes n.UseHandler(mux) http.ListenAndServe(":3000", n) ``` -------------------------------- ### Run Negroni Server Source: https://github.com/urfave/negroni/blob/master/README.md Command to run a Go server application that uses Negroni. ```bash go run server.go ``` -------------------------------- ### Basic Recovery Middleware Source: https://github.com/urfave/negroni/blob/master/README.md Use the NewRecovery() constructor to add basic panic recovery to your Negroni chain. This will catch panics and return a 500 Internal Server Error. ```go package main import ( "net/http" "github.com/urfave/negroni/v3" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { panic("oh no") }) n := negroni.New() n.Use(negroni.NewRecovery()) n.UseHandler(mux) http.ListenAndServe(":3003", n) } ``` -------------------------------- ### Recovery Middleware with HTML Panic Formatter Source: https://github.com/urfave/negroni/blob/master/README.md Use the HTMLPanicFormatter to display a user-friendly HTML page when a panic occurs. This is useful for production environments where you don't want to expose stack traces directly. ```go package main import ( "net/http" "github.com/urfave/negroni/v3" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { panic("oh no") }) n := negroni.New() recovery := negroni.NewRecovery() recovery.Formatter = &negroni.HTMLPanicFormatter{} n.Use(recovery) n.UseHandler(mux) http.ListenAndServe(":3003", n) } ``` -------------------------------- ### Route Specific Middleware with Negroni Source: https://github.com/urfave/negroni/blob/master/README.md Create a new Negroni instance to apply specific middleware to a group of routes. This is useful for isolating middleware logic. ```go router := mux.NewRouter() adminRoutes := mux.NewRouter() // add admin routes here // Create a new negroni for the admin middleware router.PathPrefix("/admin").Handler(negroni.New( Middleware1, Middleware2, negroni.Wrap(adminRoutes), )) ``` -------------------------------- ### Basic Logger Middleware Source: https://github.com/urfave/negroni/blob/master/README.md Add the NewLogger() middleware to your Negroni chain to log every incoming request and its response details. This is useful for debugging and monitoring. ```go 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.New() n.Use(negroni.NewLogger()) n.UseHandler(mux) http.ListenAndServe(":3004", n) } ``` -------------------------------- ### Custom Logger Format Source: https://github.com/urfave/negroni/blob/master/README.md Customize the log format for the Logger middleware using SetFormat() with a template string. This allows you to include specific fields like status, duration, and user agent. ```go l.SetFormat("[{{.Status}} {{.Duration}}] - {{.Request.UserAgent}}") ``` -------------------------------- ### Recovery Middleware with Custom Panic Handler Source: https://github.com/urfave/negroni/blob/master/README.md Attach a PanicHandlerFunc to the recovery middleware to report panics to an external error reporting service like Sentry. The handler receives PanicInformation about the panic. ```go package main import ( "net/http" "github.com/urfave/negroni/v3" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { panic("oh no") }) n := negroni.New() recovery := negroni.NewRecovery() recovery.PanicHandlerFunc = reportToSentry n.Use(recovery) n.UseHandler(mux) http.ListenAndServe(":3003", n) } func reportToSentry(info *negroni.PanicInformation) { // write code here to report error to Sentry } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.