From a7bae3b2a645653a149b9bcbb9bdc857e27027e2 Mon Sep 17 00:00:00 2001 From: Bas van Kervel Date: Wed, 24 Feb 2016 11:19:00 +0100 Subject: rpc/http: improve request handling --- .../src/github.com/rs/xhandler/.travis.yml | 7 ++ .../_workspace/src/github.com/rs/xhandler/LICENSE | 19 +++ .../src/github.com/rs/xhandler/README.md | 134 +++++++++++++++++++++ .../_workspace/src/github.com/rs/xhandler/chain.go | 93 ++++++++++++++ .../src/github.com/rs/xhandler/middleware.go | 59 +++++++++ .../src/github.com/rs/xhandler/xhandler.go | 42 +++++++ 6 files changed, 354 insertions(+) create mode 100644 Godeps/_workspace/src/github.com/rs/xhandler/.travis.yml create mode 100644 Godeps/_workspace/src/github.com/rs/xhandler/LICENSE create mode 100644 Godeps/_workspace/src/github.com/rs/xhandler/README.md create mode 100644 Godeps/_workspace/src/github.com/rs/xhandler/chain.go create mode 100644 Godeps/_workspace/src/github.com/rs/xhandler/middleware.go create mode 100644 Godeps/_workspace/src/github.com/rs/xhandler/xhandler.go (limited to 'Godeps/_workspace/src/github.com/rs/xhandler') diff --git a/Godeps/_workspace/src/github.com/rs/xhandler/.travis.yml b/Godeps/_workspace/src/github.com/rs/xhandler/.travis.yml new file mode 100644 index 000000000..b65c7a9f1 --- /dev/null +++ b/Godeps/_workspace/src/github.com/rs/xhandler/.travis.yml @@ -0,0 +1,7 @@ +language: go +go: +- 1.5 +- tip +matrix: + allow_failures: + - go: tip diff --git a/Godeps/_workspace/src/github.com/rs/xhandler/LICENSE b/Godeps/_workspace/src/github.com/rs/xhandler/LICENSE new file mode 100644 index 000000000..47c5e9d2d --- /dev/null +++ b/Godeps/_workspace/src/github.com/rs/xhandler/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2015 Olivier Poitrey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/Godeps/_workspace/src/github.com/rs/xhandler/README.md b/Godeps/_workspace/src/github.com/rs/xhandler/README.md new file mode 100644 index 000000000..91c594bd2 --- /dev/null +++ b/Godeps/_workspace/src/github.com/rs/xhandler/README.md @@ -0,0 +1,134 @@ +# XHandler + +[![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/xhandler) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/xhandler/master/LICENSE) [![Build Status](https://travis-ci.org/rs/xhandler.svg?branch=master)](https://travis-ci.org/rs/xhandler) [![Coverage](http://gocover.io/_badge/github.com/rs/xhandler)](http://gocover.io/github.com/rs/xhandler) + +XHandler is a bridge between [net/context](https://godoc.org/golang.org/x/net/context) and `http.Handler`. + +It lets you enforce `net/context` in your handlers without sacrificing compatibility with existing `http.Handlers` nor imposing a specific router. + +Thanks to `net/context` deadline management, `xhandler` is able to enforce a per request deadline and will cancel the context when the client closes the connection unexpectedly. + +You may create your own `net/context` aware handler pretty much the same way as you would do with http.Handler. + +Read more about xhandler on [Dailymotion engineering blog](http://engineering.dailymotion.com/our-way-to-go/). + +## Installing + + go get -u github.com/rs/xhandler + +## Usage + +```go +package main + +import ( + "log" + "net/http" + "time" + + "github.com/rs/cors" + "github.com/rs/xhandler" + "golang.org/x/net/context" +) + +type myMiddleware struct { + next xhandler.HandlerC +} + +func (h myMiddleware) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) { + ctx = context.WithValue(ctx, "test", "World") + h.next.ServeHTTPC(ctx, w, r) +} + +func main() { + c := xhandler.Chain{} + + // Add close notifier handler so context is cancelled when the client closes + // the connection + c.UseC(xhandler.CloseHandler) + + // Add timeout handler + c.UseC(xhandler.TimeoutHandler(2 * time.Second)) + + // Middleware putting something in the context + c.UseC(func(next xhandler.HandlerC) xhandler.HandlerC { + return myMiddleware{next: next} + }) + + // Mix it with a non-context-aware middleware handler + c.Use(cors.Default().Handler) + + // Final handler (using handlerFuncC), reading from the context + xh := xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + value := ctx.Value("test").(string) + w.Write([]byte("Hello " + value)) + }) + + // Bridge context aware handlers with http.Handler using xhandler.Handle() + http.Handle("/test", c.Handler(xh)) + + if err := http.ListenAndServe(":8080", nil); err != nil { + log.Fatal(err) + } +} +``` + +### Using xmux + +Xhandler comes with an optional context aware [muxer](https://github.com/rs/xmux) forked from [httprouter](https://github.com/julienschmidt/httprouter): + +```go +package main + +import ( + "fmt" + "log" + "net/http" + "time" + + "github.com/rs/xhandler" + "github.com/rs/xmux" + "golang.org/x/net/context" +) + +func main() { + c := xhandler.Chain{} + + // Append a context-aware middleware handler + c.UseC(xhandler.CloseHandler) + + // Another context-aware middleware handler + c.UseC(xhandler.TimeoutHandler(2 * time.Second)) + + mux := xmux.New() + + // Use c.Handler to terminate the chain with your final handler + mux.GET("/welcome/:name", xhandler.HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, req *http.Request) { + fmt.Fprintf(w, "Welcome %s!", xmux.Params(ctx).Get("name")) + })) + + if err := http.ListenAndServe(":8080", c.Handler(mux)); err != nil { + log.Fatal(err) + } +} +``` + +See [xmux](https://github.com/rs/xmux) for more examples. + +## Context Aware Middleware + +Here is a list of `net/context` aware middleware handlers implementing `xhandler.HandlerC` interface. + +Feel free to put up a PR linking your middleware if you have built one: + +| Middleware | Author | Description | +| ---------- | ------ | ----------- | +| [xmux](https://github.com/rs/xmux) | [Olivier Poitrey](https://github.com/rs) | HTTP request muxer | +| [xlog](https://github.com/rs/xlog) | [Olivier Poitrey](https://github.com/rs) | HTTP handler logger | +| [xstats](https://github.com/rs/xstats) | [Olivier Poitrey](https://github.com/rs) | A generic client for service instrumentation | +| [xaccess](https://github.com/rs/xaccess) | [Olivier Poitrey](https://github.com/rs) | HTTP handler access logger with [xlog](https://github.com/rs/xlog) and [xstats](https://github.com/rs/xstats) | +| [cors](https://github.com/rs/cors) | [Olivier Poitrey](https://github.com/rs) | [Cross Origin Resource Sharing](http://www.w3.org/TR/cors/) (CORS) support | + +## Licenses + +All source code is licensed under the [MIT License](https://raw.github.com/rs/xhandler/master/LICENSE). diff --git a/Godeps/_workspace/src/github.com/rs/xhandler/chain.go b/Godeps/_workspace/src/github.com/rs/xhandler/chain.go new file mode 100644 index 000000000..ffac67e8a --- /dev/null +++ b/Godeps/_workspace/src/github.com/rs/xhandler/chain.go @@ -0,0 +1,93 @@ +package xhandler + +import ( + "net/http" + + "github.com/ethereum/go-ethereum/Godeps/_workspace/src/golang.org/x/net/context" +) + +// Chain is an helper to chain middleware handlers together for an easier +// management. +type Chain []func(next HandlerC) HandlerC + +// UseC appends a context-aware handler to the middleware chain. +func (c *Chain) UseC(f func(next HandlerC) HandlerC) { + *c = append(*c, f) +} + +// Use appends a standard http.Handler to the middleware chain without +// lossing track of the context when inserted between two context aware handlers. +// +// Caveat: the f function will be called on each request so you are better to put +// any initialization sequence outside of this function. +func (c *Chain) Use(f func(next http.Handler) http.Handler) { + xf := func(next HandlerC) HandlerC { + return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + n := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + next.ServeHTTPC(ctx, w, r) + }) + f(n).ServeHTTP(w, r) + }) + } + *c = append(*c, xf) +} + +// Handler wraps the provided final handler with all the middleware appended to +// the chain and return a new standard http.Handler instance. +// The context.Background() context is injected automatically. +func (c Chain) Handler(xh HandlerC) http.Handler { + ctx := context.Background() + return c.HandlerCtx(ctx, xh) +} + +// HandlerFC is an helper to provide a function (HandlerFuncC) to Handler(). +// +// HandlerFC is equivalent to: +// c.Handler(xhandler.HandlerFuncC(xhc)) +func (c Chain) HandlerFC(xhf HandlerFuncC) http.Handler { + ctx := context.Background() + return c.HandlerCtx(ctx, HandlerFuncC(xhf)) +} + +// HandlerH is an helper to provide a standard http handler (http.HandlerFunc) +// to Handler(). Your final handler won't have access the context though. +func (c Chain) HandlerH(h http.Handler) http.Handler { + ctx := context.Background() + return c.HandlerCtx(ctx, HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + h.ServeHTTP(w, r) + })) +} + +// HandlerF is an helper to provide a standard http handler function +// (http.HandlerFunc) to Handler(). Your final handler won't have access +// the context though. +func (c Chain) HandlerF(hf http.HandlerFunc) http.Handler { + ctx := context.Background() + return c.HandlerCtx(ctx, HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + hf(w, r) + })) +} + +// HandlerCtx wraps the provided final handler with all the middleware appended to +// the chain and return a new standard http.Handler instance. +func (c Chain) HandlerCtx(ctx context.Context, xh HandlerC) http.Handler { + return New(ctx, c.HandlerC(xh)) +} + +// HandlerC wraps the provided final handler with all the middleware appended to +// the chain and returns a HandlerC instance. +func (c Chain) HandlerC(xh HandlerC) HandlerC { + for i := len(c) - 1; i >= 0; i-- { + xh = c[i](xh) + } + return xh +} + +// HandlerCF wraps the provided final handler func with all the middleware appended to +// the chain and returns a HandlerC instance. +// +// HandlerCF is equivalent to: +// c.HandlerC(xhandler.HandlerFuncC(xhc)) +func (c Chain) HandlerCF(xhc HandlerFuncC) HandlerC { + return c.HandlerC(HandlerFuncC(xhc)) +} diff --git a/Godeps/_workspace/src/github.com/rs/xhandler/middleware.go b/Godeps/_workspace/src/github.com/rs/xhandler/middleware.go new file mode 100644 index 000000000..64b180323 --- /dev/null +++ b/Godeps/_workspace/src/github.com/rs/xhandler/middleware.go @@ -0,0 +1,59 @@ +package xhandler + +import ( + "net/http" + "time" + + "github.com/ethereum/go-ethereum/Godeps/_workspace/src/golang.org/x/net/context" +) + +// CloseHandler returns a Handler cancelling the context when the client +// connection close unexpectedly. +func CloseHandler(next HandlerC) HandlerC { + return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + // Cancel the context if the client closes the connection + if wcn, ok := w.(http.CloseNotifier); ok { + var cancel context.CancelFunc + ctx, cancel = context.WithCancel(ctx) + defer cancel() + + notify := wcn.CloseNotify() + go func() { + select { + case <-notify: + cancel() + case <-ctx.Done(): + } + }() + } + + next.ServeHTTPC(ctx, w, r) + }) +} + +// TimeoutHandler returns a Handler which adds a timeout to the context. +// +// Child handlers have the responsability to obey the context deadline and to return +// an appropriate error (or not) response in case of timeout. +func TimeoutHandler(timeout time.Duration) func(next HandlerC) HandlerC { + return func(next HandlerC) HandlerC { + return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + ctx, _ = context.WithTimeout(ctx, timeout) + next.ServeHTTPC(ctx, w, r) + }) + } +} + +// If is a special handler that will skip insert the condNext handler only if a condition +// applies at runtime. +func If(cond func(ctx context.Context, w http.ResponseWriter, r *http.Request) bool, condNext func(next HandlerC) HandlerC) func(next HandlerC) HandlerC { + return func(next HandlerC) HandlerC { + return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) { + if cond(ctx, w, r) { + condNext(next).ServeHTTPC(ctx, w, r) + } else { + next.ServeHTTPC(ctx, w, r) + } + }) + } +} diff --git a/Godeps/_workspace/src/github.com/rs/xhandler/xhandler.go b/Godeps/_workspace/src/github.com/rs/xhandler/xhandler.go new file mode 100644 index 000000000..b71789804 --- /dev/null +++ b/Godeps/_workspace/src/github.com/rs/xhandler/xhandler.go @@ -0,0 +1,42 @@ +// Package xhandler provides a bridge between http.Handler and net/context. +// +// xhandler enforces net/context in your handlers without sacrificing +// compatibility with existing http.Handlers nor imposing a specific router. +// +// Thanks to net/context deadline management, xhandler is able to enforce +// a per request deadline and will cancel the context in when the client close +// the connection unexpectedly. +// +// You may create net/context aware middlewares pretty much the same way as +// you would do with http.Handler. +package xhandler + +import ( + "net/http" + + "github.com/ethereum/go-ethereum/Godeps/_workspace/src/golang.org/x/net/context" +) + +// HandlerC is a net/context aware http.Handler +type HandlerC interface { + ServeHTTPC(context.Context, http.ResponseWriter, *http.Request) +} + +// HandlerFuncC type is an adapter to allow the use of ordinary functions +// as a xhandler.Handler. If f is a function with the appropriate signature, +// xhandler.HandlerFuncC(f) is a xhandler.Handler object that calls f. +type HandlerFuncC func(context.Context, http.ResponseWriter, *http.Request) + +// ServeHTTPC calls f(ctx, w, r). +func (f HandlerFuncC) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) { + f(ctx, w, r) +} + +// New creates a conventional http.Handler injecting the provided root +// context to sub handlers. This handler is used as a bridge between conventional +// http.Handler and context aware handlers. +func New(ctx context.Context, h HandlerC) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + h.ServeHTTPC(ctx, w, r) + }) +} -- cgit