zen

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

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

Go to latest
Published: Jan 13, 2018 License: MIT Imports: 18 Imported by: 0

README

zen is a lightweight go framework for web development CircleCI

Coverage Status Go Report Card golang GoDoc license

zen is a web framework written by go, you will love it if you preffer high performance and lightweight!!!

Features

  • High performance HTTP router
  • Restful API
  • Parameters in path
  • Group APIs
  • Structure log support
  • Form validate and struct bind
  • JSON and XML data bind
  • Built in panic handler
  • Middleware at root or group level
  • Handy response functions
  • Context support
  • Graceful shutdown

Installation

go get github.com/philchia/zen

Examples

Start a server
func main() {
    server := zen.New()

    if err := server.Run(":8080"); err != nil {
        log.Println(err)
    }
}
Using GET, POST, PUT, PATCH, DELETE
    server := zen.New()
    server.Get("/test",handler)
    server.Post("/test", handler)
    server.Put("/test",handler)
    server.Patch("/test", handler)
    server.Delete("/test",handler)
Group route
    server := zen.New()

    user := server.Group("/user")
    {
        user.Get("/test",handler)
        user.Post("/test", handler)
        user.Put("/test",handler)
        user.Patch("/test", handler)
        user.Delete("/test",handler)
    }
Add a middleware
    server := zen.New()
    server.AddInterceptor(func(h HandlerFunc) HandlerFunc {
        return func(ctx zen.Context) {
            ctx.SetField("REQID",1)
            ctx.LogInfo("Root Middleware")
            h(ctx)
        }
    })
Group layer middleware
    server := zen.New()

    user := server.Group("/user")
    {
        user.AddInterceptor(func(h HandlerFunc) HandlerFunc {
        return func(ctx zen.Context) {
            ctx.LogInfo("Group Middleware")
            h(ctx)
        }
    })
    }
Parameters in path
    server := zen.New()
    server.Get("/user/:uid",func (ctx zen.Context) {
        ctx.JSON(map[string]string{"uid": ctx.Param("uid")})
    })
    if err := server.Run(":8080"); err != nil {
    log.Println(err)
    }
Parse and validate input
func handler(ctx zen.Context) {
    var input struct {
        Name string `form:"name" json:"name"`
        Age  int    `form:"age" json:"age"`
        Mail string `form:"mail" valid:"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" msg:"Illegal email" json:"mail"`
    }

    if err := ctx.ParseValidForm(&input); err != nil {
        ctx.JSON(map[string]string{"err": err.Error()})
        return
    }
    log.Println(input)
    ctx.JSON(input)
}
Handle 404
    server := zen.New()
    server.HandleNotFound(func(ctx zen.Context) {
        ctx.WriteStatus(StatusNotFound)
        ctx.WriteString(StatusText(StatusNotFound))
    })
    if err := server.Run(":8080"); err != nil {
    log.Println(err)
    }
Context support
    server := zen.New()
    server.HandleNotFound(func(ctx zen.Context) {
        ctx, cancel := ctx.WithDeadline(time.Now().Add(time.Second) * 3)
        defer cancel()
        db, _ := sql.Open("mysql", "dsn")
        db.QueryContext(ctx, "SELECT * FROM table;")
    })
    if err := server.Run(":8080"); err != nil {
    log.Println(err)
    }
Standard http.HandleFunc support
    server := zen.New()
    server.Get("/user/:uid",zen.WrapF(func(rw http.ResponseWriter, req *http.Request) {

    }))
    if err := server.Run(":8080"); err != nil {
    log.Println(err)
    }
Graceful shutdown
    server := zen.New()
    server.ShutdownDuration = time.Second * 10
    server.Shutdown()
Force close
    server := zen.New()
    server.Close()

License

zen is published under MIT license

Documentation

Overview

Package zen ... zen is a elegant and lightweight webframe for go backend development

Index

Constants

View Source
const (
	HeaderAcceptEncoding                = "Accept-Encoding"
	HeaderAllow                         = "Allow"
	HeaderAuthorization                 = "Authorization"
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLength                 = "Content-Length"
	HeaderContentType                   = "Content-Type"
	HeaderCookie                        = "Cookie"
	HeaderSetCookie                     = "Set-Cookie"
	HeaderIfModifiedSince               = "If-Modified-Since"
	HeaderLastModified                  = "Last-Modified"
	HeaderLocation                      = "Location"
	HeaderUpgrade                       = "Upgrade"
	HeaderVary                          = "Vary"
	HeaderWWWAuthenticate               = "WWW-Authenticate"
	HeaderXForwardedProto               = "X-Forwarded-Proto"
	HeaderXHTTPMethodOverride           = "X-HTTP-Method-Override"
	HeaderXForwardedFor                 = "X-Forwarded-For"
	HeaderXRealIP                       = "X-Real-IP"
	HeaderServer                        = "Server"
	HeaderOrigin                        = "Origin"
	HeaderAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge           = "Access-Control-Max-Age"

	// Security
	HeaderStrictTransportSecurity = "Strict-Transport-Security"
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderXXSSProtection          = "X-XSS-Protection"
	HeaderXFrameOptions           = "X-Frame-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
	HeaderXCSRFToken              = "X-CSRF-Token"
)

Headers

View Source
const (
	MIMEApplicationJSON                  = "application/json"
	MIMEApplicationJSONCharsetUTF8       = MIMEApplicationJSON + "; " + charsetUTF8
	MIMEApplicationJavaScript            = "application/javascript"
	MIMEApplicationJavaScriptCharsetUTF8 = MIMEApplicationJavaScript + "; " + charsetUTF8
	MIMEApplicationXML                   = "application/xml"
	MIMEApplicationXMLCharsetUTF8        = MIMEApplicationXML + "; " + charsetUTF8
	MIMEApplicationForm                  = "application/x-www-form-urlencoded"
	MIMEApplicationProtobuf              = "application/protobuf"
	MIMEApplicationMsgpack               = "application/msgpack"
	MIMETextHTML                         = "text/html"
	MIMETextHTMLCharsetUTF8              = MIMETextHTML + "; " + charsetUTF8
	MIMETextPlain                        = "text/plain"
	MIMETextPlainCharsetUTF8             = MIMETextPlain + "; " + charsetUTF8
	MIMEMultipartForm                    = "multipart/form-data"
	MIMEOctetStream                      = "application/octet-stream"
)

MIME types

View Source
const (
	// CONNECT : http method CONNECT
	CONNECT = "CONNECT"
	// DELETE : http method DELETE
	DELETE = "DELETE"
	// GET : http method GET
	GET = "GET"
	// HEAD : http method HEAD
	HEAD = "HEAD"
	// OPTIONS : http method OPTIONS
	OPTIONS = "OPTIONS"
	// PATCH : http method PATCH
	PATCH = "PATCH"
	// POST : http method POST
	POST = "POST"
	// PUT : http method PUT
	PUT = "PUT"
	// TRACE : http method TRACE
	TRACE = "TRACE"
)
View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes as registered with IANA. See: http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml

View Source
const (
	// Version is current version num
	Version = "2.0"
)

Variables

This section is empty.

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 SetLogLevel

func SetLogLevel(level string)

SetLogLevel support panic fatal error warn, warning info debug

func SetLogOutput

func SetLogOutput(out io.Writer)

SetLogOutput to an io.Writer

func StatusText

func StatusText(code int) string

StatusText returns a text for the HTTP status code. It returns the empty string if the code is unknown.

func UnWrapF

func UnWrapF(h HandlerFunc) http.HandlerFunc

UnWrapF ...

Types

type Context

type Context struct {
	Req *http.Request
	Rw  http.ResponseWriter

	context.Context
	// contains filtered or unexported fields
}

Context warps request and response writer

func (*Context) BindJSON

func (ctx *Context) BindJSON(input interface{}) error

BindJSON will parse request's json body and map into a interface{} value

func (*Context) BindXML

func (ctx *Context) BindXML(input interface{}) error

BindXML will parse request's xml body and map into a interface{} value

func (*Context) Do

func (ctx *Context) Do(job func() error) error

Do job with context

func (*Context) Dup

func (ctx *Context) Dup(c context.Context) Context

Dup make a duplicate Context with context.Context

func (*Context) Form

func (ctx *Context) Form(key string) string

Form return request form value with given key

func (*Context) GetValue

func (ctx *Context) GetValue(key interface{}) interface{}

GetValue of key

func (*Context) JSON

func (ctx *Context) JSON(i interface{}) (err error)

JSON : write json data to http response writer, with status code 200

func (*Context) LogError

func (ctx *Context) LogError(args ...interface{})

LogError print error level log with fields

func (*Context) LogErrorf

func (ctx *Context) LogErrorf(format string, args ...interface{})

LogErrorf print error level format log with fields

func (*Context) LogInfo

func (ctx *Context) LogInfo(args ...interface{})

LogInfo print info level log with fields

func (*Context) LogInfof

func (ctx *Context) LogInfof(format string, args ...interface{})

LogInfof print info level format log with fields

func (*Context) Param

func (ctx *Context) Param(key string) string

Param return url param with given key

func (*Context) ParseValidateForm

func (ctx *Context) ParseValidateForm(input interface{}) error

ParseValidateForm will parse request's form and map into a interface{} value

func (*Context) SetField

func (ctx *Context) SetField(key string, val interface{})

SetField set key val on context fields

func (*Context) SetValue

func (ctx *Context) SetValue(key, val interface{})

SetValue set value on context

func (*Context) WithCancel

func (ctx *Context) WithCancel() (Context, context.CancelFunc)

WithCancel ...

func (*Context) WithDeadline

func (ctx *Context) WithDeadline(dead time.Time) (Context, context.CancelFunc)

WithDeadline ...

func (*Context) WriteData

func (ctx *Context) WriteData(contentType string, data []byte)

WriteData writes some data into the body stream and updates the HTTP code.

func (*Context) WriteFile

func (ctx *Context) WriteFile(filepath string)

WriteFile serve file

func (*Context) WriteHeader

func (ctx *Context) WriteHeader(k, v string)

WriteHeader set response header

func (*Context) WriteStatus

func (ctx *Context) WriteStatus(code int)

WriteStatus set response's status code

func (*Context) WriteString

func (ctx *Context) WriteString(s string)

WriteString write raw string

func (*Context) XML

func (ctx *Context) XML(i interface{}) (err error)

XML : write xml data to http response writer, with status code 200

type HandlerFunc

type HandlerFunc func(Context)

HandlerFunc is a type alias for handler

func WrapF

func WrapF(h http.HandlerFunc) HandlerFunc

WrapF wrap a http handlerfunc into HandlerFunc

func (HandlerFunc) ServeHTTP

func (f HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP calls f(w, r).

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware accept a HandlerFunc and return another HandlerFunc

func WrapStdMiddleware

func WrapStdMiddleware(middleware func(http.HandlerFunc) http.HandlerFunc) Middleware

WrapStdMiddleware add support for 3rd party http middleware

type Middlewares

type Middlewares []Middleware

Middlewares contains list of Middleware

func (Middlewares) Wrap

Wrap middlewares into HandlerFunc

type Option

type Option func(*Server)

Option use to customize Server

func SetHandleMethodNotAllowed

func SetHandleMethodNotAllowed(b bool) Option

SetHandleMethodNotAllowed return Option for set HandleMethodNotAllowed

func SetHandleOPTIONS

func SetHandleOPTIONS(b bool) Option

SetHandleOPTIONS return Option for set HandleOPTIONS

func SetReadHeaderTimeout

func SetReadHeaderTimeout(t time.Duration) Option

SetReadHeaderTimeout return Option for set read header timeout

func SetReadTimeout

func SetReadTimeout(t time.Duration) Option

SetReadTimeout return Option for set read timeout

func SetRedirectFixedPath

func SetRedirectFixedPath(b bool) Option

SetRedirectFixedPath return Option for set RedirectFixedPath

func SetRedirectTrailingSlash

func SetRedirectTrailingSlash(b bool) Option

SetRedirectTrailingSlash return Option for set RedirectTrailingSlash

func SetTimeout

func SetTimeout(t time.Duration) Option

SetTimeout return Option for set timeout

func SetWriteTimeout

func SetWriteTimeout(t time.Duration) Option

SetWriteTimeout return Option for set write timeout

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 (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 Router

type Router interface {
	// Route set handler for given pattern and method
	Route(method string, path string, handler HandlerFunc)

	// Get adds a new Route for GET requests.
	Get(path string, handler HandlerFunc)

	// Post adds a new Route for POST requests.
	Post(path string, handler HandlerFunc)

	// Put adds a new Route for PUT requests.
	Put(path string, handler HandlerFunc)

	// Delete adds a new Route for DELETE requests.
	Delete(path string, handler HandlerFunc)

	// Patch adds a new Route for PATCH requests.
	Patch(path string, handler HandlerFunc)

	// Head adds a new Route for HEAD requests.
	Head(path string, handler HandlerFunc)

	// Options adds a new Route for OPTIONS requests.
	Options(path string, handler HandlerFunc)

	// Connect adds a new Route for CONNECT requests.
	Connect(path string, handler HandlerFunc)

	// Trace adds a new Route for TRACE requests.
	Trace(path string, handler HandlerFunc)

	// Any adds new Route for ALL method requests.
	Any(path string, handler HandlerFunc)

	// AddInterceptor add a interceptor for given path
	AddInterceptor(handler Middleware)
}

Router ...

type Server

type Server struct {

	// Router
	Router

	// 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

	// timeout config
	ReadTimeout       time.Duration
	WriteTimeout      time.Duration
	ReadHeaderTimeout time.Duration
	ShutdownDuration  time.Duration
	// contains filtered or unexported fields
}

Server struct

func New

func New(options ...Option) *Server

New will create a Server instance and return a pointer which point to it

func (*Server) AddInterceptor

func (s *Server) AddInterceptor(handler Middleware)

AddInterceptor add a global interceptor

func (*Server) Close

func (s *Server) Close() error

Close shutdown server forcibly

func (*Server) Group

func (s *Server) Group(base string, interceptors ...Middleware) Router

Group create a group router with base url and shared interceptors

func (*Server) HandleNotAllowed

func (s *Server) HandleNotAllowed(handler HandlerFunc)

HandleNotAllowed set server's methodNotAllowed

func (*Server) HandleNotFound

func (s *Server) HandleNotFound(handler HandlerFunc)

HandleNotFound set server's notFoundHandler

func (*Server) Lookup

func (s *Server) Lookup(method, path string) (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 (*Server) Run

func (s *Server) Run(addr string) error

Run server on addr

func (*Server) RunTLS

func (s *Server) RunTLS(addr string, certFile string, keyFile string) error

RunTLS Run server on addr with tls

func (*Server) ServeHTTP

func (s *Server) ServeHTTP(rw http.ResponseWriter, r *http.Request)

Required by http.Handler interface. This method is invoked by the http server and will handle all page routing

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown gracefully with deadline

func (*Server) Static

func (s *Server) Static(staticpath string, dir string)

Static :Adds a new Route for Static http requests. Serves static files from the specified directory

Directories

Path Synopsis
middleware

Jump to

Keyboard shortcuts

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