negroni

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 10, 2016 License: MIT Imports: 10 Imported by: 0

README

Negroni GoDoc wercker status codebeat

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:

Getting Started

After installing Go and setting up your GOPATH, create your first .go file. We'll call it server.go.

package main

import (
  "github.com/codegangsta/negroni"
  "net/http"
  "fmt"
)

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 (go 1.1 and greater is required):

go get github.com/codegangsta/negroni

Then run your server:

go run server.go

You will now have a Go net/http webserver running on localhost:3000.

Need Help?

If you have a question or feature request, go ask the mailing list. The GitHub issues for Negroni will be used exclusively for bug reports and pull requests.

Is Negroni a Framework?

Negroni is not a framework. It is a 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, Negroni tries to play well with all of them by fully supporting net/http. For instance, integrating with Gorilla Mux looks like so:

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(":3000", 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:

type Handler interface {
  ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
}

If a middleware hasn't already written to the ResponseWriter, it should call the next http.HandlerFunc in the chain to yield to the next middleware handler. This can be used for great good:

func MyMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
  // do some stuff before
  next(rw, r)
  // do some stuff after
}

And you can map it to the handler chain with the Use function:

n := negroni.New()
n.Use(negroni.HandlerFunc(MyMiddleware))

You can also map plain old http.Handlers:

n := negroni.New()

mux := http.NewServeMux()
// map your routes

n.UseHandler(mux)

http.ListenAndServe(":3000", n)

Run()

Negroni has a convenience function called Run. Run takes an addr string identical to http.ListenAndServe.

n := negroni.Classic()
n.Run(":8080")

In general, you will want to use net/http methods and just pass negroni has a handler as this is more flexible.

E.g.

  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())

Route Specific Middleware

If you have a route group of routes that need specific middleware to be executed, you can simply create a new Negroni instance and use it as your route handler.

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),
))

If you are using Gorilla Mux here is an example using a subrouter.

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),
))

Third Party Middleware

Here is a current list of Negroni compatible middlware. Feel free to put up a PR linking your middleware if you have built one:

Middleware Author Description
RestGate Prasanga Siripala Secure authentication for REST API endpoints
Graceful Tyler Bunnell Graceful HTTP Shutdown
secure Cory Jacobsen Middleware that implements a few quick security wins
JWT Middleware Auth0 Middleware checks for a JWT on the Authorization header on incoming requests and decodes it
binding Matt Holt Data binding from HTTP requests into structs
logrus Dan Buch Logrus-based logger
render Cory Jacobsen Render JSON, XML and HTML templates
gorelic Jingwen Owen Ou New Relic agent for Go runtime
gzip phyber GZIP response compression
oauth2 David Bochenski oAuth2 middleware
sessions David Bochenski Session Management
permissions2 Alexander Rødseth Cookies, users and permissions
onthefly Alexander Rødseth Generate TinySVG, HTML and CSS on the fly
cors Olivier Poitrey Cross Origin Resource Sharing (CORS) support
xrequestid Andrea Franz Middleware that assigns a random X-Request-Id header to each request
VanGoH Taylor Wrobel Configurable AWS-Style HMAC authentication middleware
stats Florent Messa Store information about your web application (response time, etc.)
prometheus Rene Zbinden Easily create metrics endpoint for the prometheus instrumentation tool
delay Jeff Martinez Add delays/latency to endpoints. Useful when testing effects of high latency

Examples

Alexander Rødseth created mooseware, a skeleton for writing a Negroni middleware handler.

Live code reload?

gin and fresh both live reload negroni apps.

Essential Reading for Beginners of Go & Negroni

About

Negroni is obsessively designed by none other than the Code Gangsta

Documentation

Overview

Package 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.

For a full guide visit http://github.com/codegangsta/negroni

package main

import (
  "github.com/codegangsta/negroni"
  "net/http"
  "fmt"
)

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()
  n.UseHandler(mux)
  n.Run(":3000")
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Handler

type Handler interface {
	ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)
}

Handler handler is an interface that objects can implement to be registered to serve as middleware in the Negroni middleware stack. ServeHTTP should yield to the next middleware in the chain by invoking the next http.HandlerFunc passed in.

If the Handler writes to the ResponseWriter, the next http.HandlerFunc should not be invoked.

func Wrap

func Wrap(handler http.Handler) Handler

Wrap converts a http.Handler into a negroni.Handler so it can be used as a Negroni middleware. The next http.HandlerFunc is automatically called after the Handler is executed.

type HandlerFunc

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

HandlerFunc is an adapter to allow the use of ordinary functions as Negroni handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler object that calls f.

func (HandlerFunc) ServeHTTP

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

type Logger

type Logger struct {
	// Logger inherits from log.Logger used to log messages with the Logger middleware
	*log.Logger
}

Logger is a middleware handler that logs the request as it goes in and the response as it goes out.

func NewLogger

func NewLogger() *Logger

NewLogger returns a new Logger instance

func (*Logger) ServeHTTP

func (l *Logger) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)

type Negroni

type Negroni struct {
	// contains filtered or unexported fields
}

Negroni is a stack of Middleware Handlers that can be invoked as an http.Handler. Negroni middleware is evaluated in the order that they are added to the stack using the Use and UseHandler methods.

func Classic

func Classic() *Negroni

Classic returns a new Negroni instance with the default middleware already in the stack.

Recovery - Panic Recovery Middleware Logger - Request/Response Logging Static - Static File Serving

func New

func New(handlers ...Handler) *Negroni

New returns a new Negroni instance with no middleware preconfigured.

func (*Negroni) Handlers added in v0.2.0

func (n *Negroni) Handlers() []Handler

Returns a list of all the handlers in the current Negroni middleware chain.

func (*Negroni) Run

func (n *Negroni) Run(addr string)

Run is a convenience function that runs the negroni stack as an HTTP server. The addr string takes the same format as http.ListenAndServe.

func (*Negroni) ServeHTTP

func (n *Negroni) ServeHTTP(rw http.ResponseWriter, r *http.Request)

func (*Negroni) Use

func (n *Negroni) Use(handler Handler)

Use adds a Handler onto the middleware stack. Handlers are invoked in the order they are added to a Negroni.

func (*Negroni) UseFunc added in v0.2.0

func (n *Negroni) UseFunc(handlerFunc func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc))

UseFunc adds a Negroni-style handler function onto the middleware stack.

func (*Negroni) UseHandler

func (n *Negroni) UseHandler(handler http.Handler)

UseHandler adds a http.Handler onto the middleware stack. Handlers are invoked in the order they are added to a Negroni.

func (*Negroni) UseHandlerFunc added in v0.2.0

func (n *Negroni) UseHandlerFunc(handlerFunc func(rw http.ResponseWriter, r *http.Request))

UseHandler adds a http.HandlerFunc-style handler function onto the middleware stack.

type Recovery

type Recovery struct {
	Logger     *log.Logger
	PrintStack bool
	StackAll   bool
	StackSize  int
}

Recovery is a Negroni middleware that recovers from any panics and writes a 500 if there was one.

func NewRecovery

func NewRecovery() *Recovery

NewRecovery returns a new instance of Recovery

func (*Recovery) ServeHTTP

func (rec *Recovery) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)

type ResponseWriter

type ResponseWriter interface {
	http.ResponseWriter
	http.Flusher
	// Status returns the status code of the response or 0 if the response has not been written.
	Status() int
	// Written returns whether or not the ResponseWriter has been written.
	Written() bool
	// Size returns the size of the response body.
	Size() int
	// Before allows for a function to be called before the ResponseWriter has been written to. This is
	// useful for setting headers or any other operations that must happen before a response has been written.
	Before(func(ResponseWriter))
}

ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a responsewriter if the functionality calls for it.

func NewResponseWriter

func NewResponseWriter(rw http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter

type Static

type Static struct {
	// Dir is the directory to serve static files from
	Dir http.FileSystem
	// Prefix is the optional prefix used to serve the static directory content
	Prefix string
	// IndexFile defines which file to serve as index if it exists.
	IndexFile string
}

Static is a middleware handler that serves static files in the given directory/filesystem.

func NewStatic

func NewStatic(directory http.FileSystem) *Static

NewStatic returns a new instance of Static

func (*Static) ServeHTTP

func (s *Static) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL