7,527
stars
+0+-1+0
571
forks
–
watchers
–
prs
–
issues
–
releases
–
discussions
README
Negroni
Notice: This is the library formerly known as
github.com/codegangsta/negroni -- Github will automatically redirect requests
to this repository, but we recommend updating your references for clarity.
Import path: use the current major module path
github.com/urfave/negroni/v3 (v3 is the latest release). Older docs and
copy-pasted snippets may still show github.com/urfave/negroni without /v3.
Negroni is an idiomatic approach to web middleware in Go. It is tiny,
non-intrusive, and encourages use of net/http Handlers.
If you like the idea of Martini, but
you think it contains too much magic, then Negroni is a great fit.
Language Translations:
Deutsch (de_DE)
Português Brasileiro (pt_BR)
简体中文 (zh_CN)
繁體中文 (zh_TW)
日本語 (ja_JP)
Français (fr_FR)
한국어 (ko_KR)
Getting Started
After installing Go and setting up your
GOPATH, create your first .go file.
We'll call it server.go.
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)
}
Then install the Negroni package (NOTE: >= go 1.1 is required):
go get github.com/urfave/negroni/v3
Then run your server:
go run server.go
You will now have a Go net/http webserver running on localhost:3000.
Packaging
If you are on Debian, negroni is also available as a
package that
you can install via apt install golang-github-urfave-negroni-dev (at the time
of writing, it is in the sid repositories).
Is Negroni a Framework?
Negroni is not a framework. It is a middleware-focused library that is
designed to work directly with net/http.
Routing?
Negroni is BYOR (Bring your own Router). The Go community already has a number
of great http routers available, and Negroni tries to play well with all of them
by fully supporting net/http. For instance, integrating with [Gorilla Mux]
looks like so:
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)
negroni.Classic()
negroni.Classic() provides some default middleware that is useful for most
applications:
negroni.Recovery - Panic Recovery Middleware.
negroni.Logger - Request/Response Logger Middleware.
negroni.Static - Static File serving under the "public"
directory.
This makes it really easy to get started with some useful features from Negroni.
Handlers
Negroni provides a bidirectional middleware flow. This is done through the
negroni.Handler interface:
go
type Handler interface {
ServeHTTP(rw http.ResponseWriter, r http.Request, next http.HandlerFunc)
}
If a middleware hasn't already written to the ResponseWriter, it