Code Monkey home page Code Monkey logo

negroni's Introduction

Negroni GoDoc wercker status

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.

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

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)

n.Run(":3000")

negroni.Classic()

negroni.Classic() provides some default middleware that is useful for most applications:

  • negroni.Recovery - Panic Recovery Middleware.
  • negroni.Logging - Request/Response Logging 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.Handler's:

n := negroni.New()

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

n.UseHandler(mux)

n.Run(":3000")

Run()

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

n := negroni.Classic()
// ...
log.Fatal(http.ListenAndServe(":8080", n))

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.Handle("/admin", negroni.New(
  Middleware1, 
  Middleware2, 
  negroni.Wrap(adminRoutes),
))

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
Graceful Tyler Bunnell Graceful HTTP Shutdown
secure Cory Jacobsen Middleware that implements a few quick security wins
binding Matt Holt Data binding from HTTP requests into structs
logrus Dan Buch Logrus-based logger
render Cory Jacobsen Package for rendering 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

Live code reload?

gin and fresh both live reload negroni apps.

About

Negroni is obsessively designed by none other than the Code Gangsta

negroni's People

Contributors

codegangsta avatar peterbourgon avatar mdlayher avatar bochenski avatar stengaard avatar unrolled avatar meatballhat avatar owenthereal avatar mholt avatar nodirt avatar

Watchers

Ray Leyva avatar James Cloos avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.