easy_middleware

package module
Version: v1.6.0 Latest Latest
Warning

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

Go to latest
Published: May 13, 2017 License: MIT Imports: 14 Imported by: 0

README

Build Status

easy-middleware

What is easy-middleware ?

easy-middleware is a lightweight json middleware stack for Go >= 1.7.

Features:

  • Dump incoming request middleware
  • Set body limit middleware
  • Json header check middleware
  • Validator middleware
  • Sql db middleware
  • Recovery middleware
  • With value middleware
  • Json response writer middleware

Feature request are welcome

Example :

    package main

    import (
        "net/http"
        "github.com/donutloop/easy-middleware"
    )

    func main() {

        stack := easy_middleware.New()
    	stack.Add(easy_middleware.Json())
    	stack.Add(easy_middleware.SqlDb("postgres", "postgres://postgres:postgres@db/postgres?sslmode=disable"))
    
        http.Handle("/user", stack.Then(http.HandlerFunc(userHandler)))
        http.ListenAndServe(":80", nil)
    }

    func userHandler(rw http.ResponseWriter, req *http.Request) {
         jrw := rw.(*easy_middleware.JsonResponseWriter)          
          
         var db *sql.DB
         if rv := r.Context().Value("db"); rv != nil {
         		if v, ok := rv.(*sql.DB); ok {
         			 db = v 
         		} else if err := rv.(*easy_middleware.DatabaseError); err != nil {
         			 jrw.WriteError(err, http.StatusInternalServerError)
         			 return 
         		}
         }  
        //...
        
    }

More documentation comming soon

Documentation

Index

Constants

View Source
const DELAY_HEADER_KEY = "X-Add-Delay"
View Source
const SqlDbContextKey contextKey = "sqldb"
View Source
const URLQueryKey contextKey = "urlquery"

URLQueryKey is the context key for the URL Query

Variables

View Source
var Close = close
View Source
var Open = open

Functions

func WriteJsonError

func WriteJsonError(w http.ResponseWriter, v ErrorResponse, code int) (int, error)

Types

type Chain

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

Chain acts as a list of middleware. Chain is effectively immutable: once created, it will always hold the same set of constructors in the same order.

func Create

func Create(chain Chain, middleware ...Middleware) Chain

Create a chain, adding the specified middleware as the last ones in the request flow.

stdChain := easy_middleware.New(m1, m2)
extChain := Create(stdChain, m3, m4)
// requests in stdChain go m1 -> m2
// requests in extChain go m1 -> m2 -> m3 -> m4

func Merge

func Merge(chainOne, chainTwo Chain) Chain

Merge two chains Returns a new chain, leaving the originals one untouched.

stdChain := easy_middleware.New(m1, m2)
stdChain := easy_middleware.New(m3, m4)
mergedChain := Merge(m3, m4)
// requests in stdChain go m1 -> m2
// requests in extChain go m1 -> m2 -> m3 -> m4

func New

func New(middleware ...Middleware) Chain

New creates a new chain, memorizing the given list of middleware. New serves no other function, constructors are only called upon a call to Then().

func (*Chain) Add

func (c *Chain) Add(middleware ...Middleware)

Add a middleware to a existing chain stdChain := easy_middleware.New(m1, m2) stdChainCopy := stdChain.Copy() stdChainCopy := stdChain.Add(m1) or stdChainCopy := stdChain.Add(m1, m2)

func (Chain) Copy

func (c Chain) Copy() Chain

Copy middleware of existing chain and takes that as base for a new chain stdChain := easy_middleware.New(m1, m2) stdChainCopy := stdChain.Copy()

func (Chain) Then

func (c Chain) Then(endpoint http.Handler) http.Handler

Then chains the middleware and returns the final http.Handler.

New(m1, m2, m3).Then(h)

is equivalent to:

m1(m2(m3(h)))

When the request comes in, it will be passed to m1, then m2, then m3 and finally, the given handler (assuming every middleware calls the following one).

A chain can be safely reused by calling Then() several times.

stdStack := easy_middleware.New(ratelimitHandler, csrfHandler)
indexPipe = stdStack.Then(indexHandler)
authPipe = stdStack.Then(authHandler)

Note that constructors are called on every call to Then() and thus several instances of the same middleware will be created when a chain is reused in this way. For proper middleware, this should cause no problems.

Then() treats nil as http.DefaultServeMux.

func (Chain) ThenFunc

func (c Chain) ThenFunc(endpointFunc http.HandlerFunc) http.Handler

ThenFunc works identically to Then, but takes a HandlerFunc instead of a Handler.

The following two statements are equivalent:

c.Then(http.HandlerFunc(fn))
c.ThenFunc(fn)

ThenFunc provides all the guarantees of Then.

type DatabaseError

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

DatabaseError represenst a error for bad database connection, it's occurs while a request process

func (*DatabaseError) Error

func (e *DatabaseError) Error() string

type ErrorEntity

type ErrorEntity struct {
	// Code is the HTTP response status code and will always be populated.
	Code    int         `json:"code"`
	Message interface{} `json:"message"`
}

type ErrorResponse

type ErrorResponse struct {
	Error ErrorEntity `json:"error"`
}

func NewError

func NewError(message interface{}, code int) ErrorResponse

type JsonResponseWriter

type JsonResponseWriter struct {
	http.ResponseWriter
}

It implements the following interfaces: ResponseWriter http.ResponseWriter http.Flusher http.CloseNotifier http.Hijacker

func (*JsonResponseWriter) CloseNotify

func (w *JsonResponseWriter) CloseNotify() <-chan bool

Call the parent CloseNotify. Provided in order to implement the http.CloseNotifier interface.

func (*JsonResponseWriter) EncodeJson

func (w *JsonResponseWriter) EncodeJson(v interface{}) ([]byte, error)

Replace the parent EncodeJson to provide indentation.

func (*JsonResponseWriter) Flush

func (w *JsonResponseWriter) Flush()

Make sure the local WriteHeader is called, and call the parent Flush. Provided in order to implement the http.Flusher interface.

func (*JsonResponseWriter) Header

func (w *JsonResponseWriter) Header() http.Header

func (*JsonResponseWriter) Hijack

func (w *JsonResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Provided in order to implement the http.Hijacker interface.

func (*JsonResponseWriter) Write

func (w *JsonResponseWriter) Write(b []byte) (int, error)

Make sure the local WriteHeader is called, and call the parent Write. Provided in order to implement the http.ResponseWriter interface.

func (*JsonResponseWriter) WriteError

func (w *JsonResponseWriter) WriteError(herr interface{}, code int) error

func (*JsonResponseWriter) WriteHeader

func (w *JsonResponseWriter) WriteHeader(code int)

Call the parent WriteHeader.

func (*JsonResponseWriter) WriteJson

func (w *JsonResponseWriter) WriteJson(v interface{}) error

Make sure the local EncodeJson and local Write are called. Does not call the parent WriteJson.

type Middleware

type Middleware func(http.Handler) http.Handler

func Cors

func Cors(defaultHeaders string) Middleware

CORS Middleware creates a new CORS Middleware with default headers.

func Delay added in v1.6.0

func Delay() Middleware

decimal numbers, each with optional fraction and a unit suffix, such as "300ms", "-1.5h" or "2h45m".

func DumpIncomingRequest

func DumpIncomingRequest(logger *log.Logger) Middleware

Dump request middleware creates a dump of in coming request.

func Json

func Json() Middleware

Set the Content-Type header 'application/json'

func JsonHeaderCheck

func JsonHeaderCheck() Middleware

Verifies the request Content-Type header and returns a StatusUnsupportedMediaType (415) HTTP error response if it's incorrect. The expected Content-Type is 'application/json' if the content is non-null. Note: If a charset parameter exists, it MUST be UTF-8.

func Logging

func Logging(callback func(s string)) Middleware

Logging of device request time

func NoCache added in v1.3.0

func NoCache() Middleware

NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent a router from being cached by an upstream proxy and/or client.

func Recovery

func Recovery(callback func(requestDump []byte, stackDump []byte)) Middleware

Recovery middleware for panic

func SetBodyLimit

func SetBodyLimit(limit int64) Middleware

func SqlDb

func SqlDb(databaseDriver string, dsn string) Middleware

SqlDb is a middlware for creating a unique session for each incomming request

func Timeout added in v1.5.0

func Timeout(timeoutAfter time.Duration) Middleware

Timeout is a middleware that cancels ctx after a given timeout and return a 504 Gateway Timeout error to the client.

func URLQuery added in v1.2.0

func URLQuery() Middleware

URLQuery is a middleware to parse the URL Query parameters just once, and store the resulting url.Values in the context.

func WithValue added in v1.1.0

func WithValue(key interface{}, val interface{}) Middleware

WithValue is a middleware that sets a given key/value in the request context.

type Queries added in v1.2.0

type Queries struct {
	C map[string][]string
}

func (Queries) Count added in v1.2.0

func (q Queries) Count() int

Count returns count of the current *http.Request queries

func (Queries) Get added in v1.2.0

func (q Queries) Get(key string) []string

Get return the key value, of the current *http.Request queries

func (Queries) GetAll added in v1.2.0

func (q Queries) GetAll() map[string][]string

Get returns all queries of the current *http.Request queries

Jump to

Keyboard shortcuts

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