vermouth

package module
v0.0.0-...-da1f214 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2017 License: MIT Imports: 12 Imported by: 0

README

Vermouth

Vermouth is context friendly web framework. This has dead simple and flexible interface. This project is heavily inspired by negroni and kami.

Features

  • flexible middleware stack like negroni

  • include httprouter based router

  • context-based graceful shutdown support

Examples

package main

import (
	"github.com/bluele/vermouth"

    "context"
	"fmt"
	"net/http"
)

func main() {
	vm := vermouth.New()
	vm.Use("/", func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
		fmt.Fprint(w, "start:")
		defer fmt.Fprint(w, ":end")
		// call next middleware
		next(w, vermouth.WithValue(r, "key", "value"))
	})
	vm.Get("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, r.Context().Value("key").(string))
	})
	vm.Serve(":3000")
}

// $ curl 127.0.0.1:3000/
// start:value:end

Middleware stack

vermouth implements hierarchical structures like negroni. Here is example:

vm.Use("/", Middleware1)
vm.Use("/", Middleware2)
vm.Get("/", HTTPHandler)

In above case, normally call stack is:

Request ->
Middleware1 -> Middleware2 ->
HTTPHandler ->
Middleware2 -> Middleware1 ->
Response

Graceful shutdown support

Vermouth includes context-based graceful shutdown support.

Vermouth server observe the status of context object. If context.Done() returns a value, vermouth will be shutdown gracefully.

See following example:

func main() {
    // This server will be shutdown after 10 sec.
	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	vm := vermouth.New().WithContext(ctx)

	vm.Get("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "hello")
	})
	vm.Serve(":3000")
	log.Println("shutdown...")
}

See detail configurations: godoc, tylerb/graceful

Contribution

  1. Fork (https://github.com/bluele/vermouth/fork)
  2. Create a feature branch
  3. Commit your changes
  4. Rebase your local changes against the master branch
  5. Run test suite with the go test ./... command and confirm that it passes
  6. Run gofmt -s
  7. Create new Pull Request

Author

Jun Kimura

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ParamsCtxKey = "vermouth.Params"

ParamsCtxKey is a key to be used when Params object is bound to context object.

Functions

func CleanPath

func CleanPath(p string) string

CleanPath is the URL version of path.Clean, it returns a canonical URL path for p, eliminating . and .. elements.

The following rules are applied iteratively until no further processing can be done:

  1. Replace multiple slashes with a single slash.
  2. Eliminate each . path name element (the current directory).
  3. Eliminate each inner .. path name element (the parent directory) along with the non-.. element that precedes it.
  4. Eliminate .. elements that begin a rooted path: that is, replace "/.." by "/" at the beginning of a path.

If the result of this process is an empty string, "/" is returned

func NewPathContext

func NewPathContext(ctx context.Context, params Params) context.Context

func WithValue

func WithValue(r *http.Request, key, value interface{}) *http.Request

Types

type Handler

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

Handler is an interface that objects can implement to be registered to serve as middleware in the Vermouth 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.

type HandlerFunc

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

HandlerFunc is an adapter to allow the use of ordinary functions as Vermouth 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(w http.ResponseWriter, r *http.Request, next http.HandlerFunc)

type HandlerType

type HandlerType interface{}

HandlerType is the type of Handlers and types that vermouth internally converts to http.HandlerFunc. In order to provide an expressive API, this type is an alias for interface{} that is named for the purposes of documentation, however only the following concrete types are accepted:

  • func(http.ResponseWriter, *http.Request)
  • types that implement http.Handler

type MiddlewareType

type MiddlewareType interface{}

MiddlewareType represents types that vermouth can convert to Middleware. vermouth will try its best to convert standard, non-context middleware. See the Use function for important information about how vermouth middleware is run. The following concrete types are accepted:

  • types that implement Handler
  • func(http.ResponseWriter, *http.Request, http.HandlerFunc)

type Options

type Options struct {
	ReadTimeout    time.Duration // maximum duration before timing out read of the request
	WriteTimeout   time.Duration // maximum duration before timing out write of the response
	MaxHeaderBytes int           // maximum size of request headers, DefaultMaxHeaderBytes if 0
	TLSConfig      *tls.Config   // optional TLS config, used by ListenAndServeTLS

	// TLSNextProto optionally specifies a function to take over
	// ownership of the provided TLS connection when an NPN
	// protocol upgrade has occurred.  The map key is the protocol
	// name negotiated. The Handler argument should be used to
	// handle HTTP requests and will initialize the Request's TLS
	// and RemoteAddr if not already set.  The connection is
	// automatically closed when the function returns.
	// If TLSNextProto is nil, HTTP/2 support is enabled automatically.
	TLSNextProto map[string]func(*http.Server, *tls.Conn, http.Handler)

	// ConnState specifies an optional callback function that is
	// called when a client connection changes state. See the
	// ConnState type and associated constants for details.
	ConnState func(net.Conn, http.ConnState)

	// Timeout is the duration to allow outstanding requests to survive
	// before forcefully terminating them.
	GracefulTimeout time.Duration

	// Limit the number of outstanding requests
	ListenLimit int

	// ShutdownInitiated is an optional callback function that is called
	// when shutdown is initiated. It can be used to notify the client
	// side of long lived connections (e.g. websockets) to reconnect.
	ShutdownInitiated func()

	// NoSignalHandling prevents graceful from automatically shutting down
	// on SIGINT and SIGTERM. If set to true, you must shut down the server
	// manually with Stop().
	NoSignalHandling bool

	// ErrorLog specifies an optional logger for errors accepting
	// connections and unexpected behavior from handlers.
	// If nil, logging goes to os.Stderr via the log package's
	// standard logger.
	ErrorLog *log.Logger
}

Options for vermouth app This is used by initializing http.Server and graceful.Server

type Param

type Param struct {
	Key   string
	Value string
}

Param is a single URL parameter, consisting of a key and a value.

type Params

type Params []Param

Params is a Param-slice, as returned by the router. The slice is ordered, the first URL parameter is also the first slice value. It is therefore safe to read values by the index.

func Path

func Path(ctx context.Context) Params

func (Params) ByName

func (ps Params) ByName(name string) string

ByName returns the value of the first Param which key matches the given name. If no matching Param is found, an empty string is returned.

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(w http.ResponseWriter) ResponseWriter

NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter

type Router

type Router struct {

	// Enables automatic redirection if the current route can't be matched but a
	// handler for the path with (without) the trailing slash exists.
	// For example if /foo/ is requested but a route only exists for /foo, the
	// client is redirected to /foo with http status code 301 for GET requests
	// and 307 for all other request methods.
	RedirectTrailingSlash bool

	// If enabled, the router tries to fix the current request path, if no
	// handle is registered for it.
	// First superfluous path elements like ../ or // are removed.
	// Afterwards the router does a case-insensitive lookup of the cleaned path.
	// If a handle can be found for this route, the router makes a redirection
	// to the corrected path with status code 301 for GET requests and 307 for
	// all other request methods.
	// For example /FOO and /..//Foo could be redirected to /foo.
	// RedirectTrailingSlash is independent of this option.
	RedirectFixedPath bool

	// If enabled, the router checks if another method is allowed for the
	// current route, if the current request can not be routed.
	// If this is the case, the request is answered with 'Method Not Allowed'
	// and HTTP status code 405.
	// If no other Method is allowed, the request is delegated to the NotFound
	// handler.
	HandleMethodNotAllowed bool

	// If enabled, the router automatically replies to OPTIONS requests.
	// Custom OPTIONS handlers take priority over automatic replies.
	HandleOPTIONS bool

	// Configurable http.Handler which is called when no matching route is
	// found. If it is not set, http.NotFound is used.
	NotFound http.Handler

	// Configurable http.Handler which is called when a request
	// cannot be routed and HandleMethodNotAllowed is true.
	// If it is not set, http.Error with http.StatusMethodNotAllowed is used.
	// The "Allow" header with allowed request methods is set before the handler
	// is called.
	MethodNotAllowed http.Handler

	// Function to handle panics recovered from http handlers.
	// It should be used to generate a error page and return the http error code
	// 500 (Internal Server Error).
	// The handler can be used to keep your server from crashing because of
	// unrecovered panics.
	PanicHandler func(http.ResponseWriter, *http.Request, interface{})
	// contains filtered or unexported fields
}

Router is a http.Handler which can be used to dispatch requests to different handler functions via configurable routes

func NewRouter

func NewRouter() *Router

NewRouter returns a new initialized Router. Path auto-correction, including trailing slashes, is enabled by default.

func (*Router) DELETE

func (r *Router) DELETE(path string, handle http.HandlerFunc)

DELETE is a shortcut for router.Handle("DELETE", path, handle)

func (*Router) GET

func (r *Router) GET(path string, handle http.HandlerFunc)

GET is a shortcut for router.Handle("GET", path, handle)

func (*Router) HEAD

func (r *Router) HEAD(path string, handle http.HandlerFunc)

HEAD is a shortcut for router.Handle("HEAD", path, handle)

func (*Router) Handle

func (r *Router) Handle(method, path string, handle http.HandlerFunc)

Handle registers a new request handle with the given path and method.

For GET, POST, PUT, PATCH and DELETE requests the respective shortcut functions can be used.

This function is intended for bulk loading and to allow the usage of less frequently used, non-standardized or custom methods (e.g. for internal communication with a proxy).

func (*Router) Handler

func (r *Router) Handler(method, path string, handler http.Handler)

Handler is an adapter which allows the usage of an http.Handler as a request handle.

func (*Router) HandlerFunc

func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc)

HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a request handle.

func (*Router) Lookup

func (r *Router) Lookup(method, path string) (http.HandlerFunc, Params, bool)

Lookup allows the manual lookup of a method + path combo. This is e.g. useful to build a framework around this router. If the path was found, it returns the handle function and the path parameter values. Otherwise the third return value indicates whether a redirection to the same path with an extra / without the trailing slash should be performed.

func (*Router) OPTIONS

func (r *Router) OPTIONS(path string, handle http.HandlerFunc)

OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)

func (*Router) PATCH

func (r *Router) PATCH(path string, handle http.HandlerFunc)

PATCH is a shortcut for router.Handle("PATCH", path, handle)

func (*Router) POST

func (r *Router) POST(path string, handle http.HandlerFunc)

POST is a shortcut for router.Handle("POST", path, handle)

func (*Router) PUT

func (r *Router) PUT(path string, handle http.HandlerFunc)

PUT is a shortcut for router.Handle("PUT", path, handle)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP makes the router implement the http.Handler interface.

type Vermouth

type Vermouth struct {
	Options *Options
	// contains filtered or unexported fields
}

Vermouth object

func New

func New() *Vermouth

New creates a new independent router and middleware stack.

func (*Vermouth) Get

func (vm *Vermouth) Get(pattern string, handler HandlerType) *Vermouth

Get registers a GET handler under the given path.

func (*Vermouth) Handle

func (vm *Vermouth) Handle(method, pattern string, handler HandlerType) *Vermouth

Handle registers an arbitrary method handler under the given path.

func (*Vermouth) HandlerFunc

func (vm *Vermouth) HandlerFunc() http.HandlerFunc

func (*Vermouth) Middlewares

func (vm *Vermouth) Middlewares() []Handler

Middlewares returns registered handlers.

func (*Vermouth) NewServer

func (vm *Vermouth) NewServer() *graceful.Server

NewServer returns a new server implements http.Server.

func (*Vermouth) ObserveContext

func (vm *Vermouth) ObserveContext(srv *graceful.Server)

ObserveContext observe the status for top level context object. If context is done, shutdown a server gracefully.

func (*Vermouth) Post

func (vm *Vermouth) Post(pattern string, handler HandlerType) *Vermouth

Post registers a GET handler under the given path.

func (*Vermouth) Serve

func (vm *Vermouth) Serve(addr string) error

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

func (*Vermouth) ServeHTTP

func (vm *Vermouth) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*Vermouth) ServeListener

func (vm *Vermouth) ServeListener(l net.Listener) error

ServeListener is like Serve, but runs vermouth on top of an arbitrary net.Listener.

func (*Vermouth) SetRouter

func (vm *Vermouth) SetRouter(router *Router) *Vermouth

SetRouter sets a router object

func (*Vermouth) Use

func (vm *Vermouth) Use(pattern string, mw MiddlewareType) *Vermouth

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

func (*Vermouth) WithContext

func (vm *Vermouth) WithContext(ctx context.Context) *Vermouth

WithContext sets a root context object. All request context will be derive from this context.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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