Code Monkey home page Code Monkey logo

moon's Introduction

Moon

Build Status Coverage Status MIT licensed GoDoc

Moon is a simple middleware chaining system with requests context handled by /x/net/context context.Context

No magic GO code is required to use Moon.

Quick tour

Middlewares use this signature

func (context.Context, moon.Next) http.Handler

and final handler

func handler(context.Context) http.Handler

Middlewares are chained with moon.New

middlewares := moon.New(middleware1, middleware2, middleware3, ...)

moon.New returns a Moon struct.

The final handler is appended by passing moon.Handler to Moon.Then

r.Handle("/api", middlewares.Then(handler))

or by passing a function to Moon.ThenFunc

r.Handle("/api", middlewares.ThenFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  ...
}))

Inside a middleware you can advance the chain by calling next(ctx)

func Middleware(ctx context.Context, next moon.Next) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // ...
    next(ctx)
    // ...
  })
}

contex.TODO() or appengine.NewContext(request) ?

By default a context.Context is created for each request and is an instance of

ctx := context.TODO()

this behaviour can be modified by setting a callback for moon.Context ie. if you run you app in appengine:

func init() {
  ...

  // just setup it once; then this function is called for every request
  moon.Context = func(r *http.Request) {
    return appengine.NewContext(r)
  }  

  ...
}

Included middlewares

Panic

Recover from panics with status code http.StatusInternalServerError and a dump of the goroutine stack trace

middlewares := moon.New(moon.Panic, ...).Then(...)

3rd party middlewares

Compatibility is provided with all 3rd party middlewares using the following signature

func (http.Handler) http.Handler

just wrap the function with

moon.Adapt

ie. GOJI SimpleBasicAuth

goji_middleware := moon.Adapt(httpauth.SimpleBasicAuth("user", "pass"))
middlewares := moon.New(goji_middlware, ...).Then(...)

Quick example

// Appengine test app
package app

import (
	"fmt"
	"net/http"

	"google.golang.org/appengine"

	"golang.org/x/net/context"

	"github.com/gorilla/mux"
	"github.com/nferruzzi/moon"
)

func MWRequireJSON(ctx context.Context, next moon.Next) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ct := r.Header.Get("Content-Type")
		if ct == "application/json" {
			ctx = context.WithValue(ctx, "Content-Type", ct)
			next(ctx)
		} else {
			w.WriteHeader(http.StatusBadRequest)
		}
	})
}

func MWRequireUser(ctx context.Context, next moon.Next) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// let's pretend some checks are made
		ctx = context.WithValue(ctx, "User", "user")
		next(ctx)
	})
}

func handler(ctx context.Context) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "Hello %v! thanks for your %v", ctx.Value("User"), ctx.Value("Content-Type"))
	})
}

func init() {
	// Appengine only: configure moon to get the context from the request
	// Common default is context.TODO()
	moon.Context = func(r *http.Request) context.Context {
		return appengine.NewContext(r)
	}

	// Middlewares chain
	middlewares := moon.New(MWRequireJSON, MWRequireUser)

	// Use gorilla mux to route and handle the request
	r := mux.NewRouter()
	r.Handle("/api", middlewares.Then(handler))

	http.Handle("/", r)
}

// curl -H Content-Type:application/json http://localhost:8080/api
// Hello user! thanks for your application/json✔ ~

Stability

API is under development.

Acknowledgements

Thanks to the authors of the package below, I got a lot of idea from your code

Using contex.Context inspired by kami and appengine

https://github.com/guregu/kami

Middleware chaining inspired by Alice

https://github.com/justinas/alice

and by Stack

https://github.com/alexedwards/stack

Bidirectional middleware flow inspired by Negroni

https://github.com/codegangsta/negroni

Tested with GOJI middlewares

https://github.com/goji/goji

moon's People

Contributors

nferruzzi avatar cybercase avatar

Stargazers

Ivan Nikolaev avatar Matteo Bertini avatar

Watchers

James Cloos avatar  avatar  avatar

Forkers

cybercase

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.