umeshu

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

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

Go to latest
Published: Jul 2, 2022 License: MIT Imports: 16 Imported by: 0

README

Umeshu

Umeshu is a mini web framework written by Golang.

Purpose

Why do I reinvent the wheel? Just for learning. 😊

Building a mini web framework from scratch using Go standard library such as net/http, container/list, sync, pprof, runtime, etc.

Features

Umeshu has the following features:

  1. radix tree based routing
    • parameter pattern
    • wildcard pattern
    • path parameter matching
  2. routes grouping
  3. middleware support
  4. crash-free
    • auto recovery when panic
    • internal server error response
    • trackback log
  5. multi-level loggers
  6. cache based session
  7. pprof support
  8. graceful shutdown

References

  1. Gin Web Framework
  2. echo
  3. 7 days golang programs from scratch
  4. Build Web Application with Golang

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	HTTP404Handler func(c *Context)
	HTTP500Handler func(c *Context)
)

Functions

func NewRootNode

func NewRootNode() *routerNode

NewRootNode creates and returns new *routerNode.

func SetRouter

func SetRouter(router Router)

SetRouter sets the global router.

Types

type Context

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

	// provide direct access info extracts from request for convenience
	Path        string
	Method      string
	RouteParams map[string]string

	StatusCode int // status code for response
	// contains filtered or unexported fields
}

Context represents the context of the current HTTP request. It contains path, route parameters, session and registered handlers. It also holds request and response objects.

func NewContext

func NewContext(rw http.ResponseWriter, r *http.Request) *Context

NewContext return a new context instance from context pool.

func (*Context) Data

func (c *Context) Data(code int, data []byte)

Data responses http request by returning data specified

func (*Context) EndSession

func (c *Context) EndSession()

EndSession ends session.

func (*Context) Exit

func (c *Context) Exit(exitHandler HandlerFunc)

Exit skips the remaining middlewares/handlers and executes exit handler.

Note: It will still execute those code after c.Next() of those middlewares and those defer functions.

Warning: It will also skip the handler registered. Re-define handler in exit handler to handle it if it is necessary.

func (*Context) Fail

func (c *Context) Fail(code int, err string)

Fail responses http request by returning error message specified

func (*Context) FormValue

func (c *Context) FormValue(key string) string

Wrapper function of (*http.Request).FormValue(key string) string.

func (*Context) Free

func (c *Context) Free()

Free frees the context object and put it into context pool.

func (*Context) GetQuery

func (c *Context) GetQuery(key string) string

Wrapper function of (url.Values).Get(key string) string.

func (*Context) GetRouteParam

func (c *Context) GetRouteParam(key string) string

GetRouteParam returns route parameters.

func (*Context) GetSession

func (c *Context) GetSession() session.Session

GetSession gets session object, will implicitly call (c *Context).StartSession() if there is no session object exists.

func (*Context) HTML

func (c *Context) HTML(code int, html string)

HTML responses http request by returning a static html page

func (*Context) HTMLTemplate

func (c *Context) HTMLTemplate(code int, name string, data interface{})

HTMLTemplate responses http request by returning a html page according to template specified.

func (*Context) Init

func (c *Context) Init(rw http.ResponseWriter, r *http.Request)

Init sets the initinal values for new context.

func (*Context) JSON

func (c *Context) JSON(code int, object interface{})

JSON responses http request by returning JSON object

func (*Context) Next

func (c *Context) Next()

Next runs the next middleware/handler.

func (*Context) Redirect

func (c *Context) Redirect(code int, to string)

Redirect redicects route to another path.

func (*Context) SetHeader

func (c *Context) SetHeader(key string, value string)

func (*Context) SetStatus

func (c *Context) SetStatus(code int)

func (*Context) StartSession

func (c *Context) StartSession()

StartSession returns existing session or starts new session if no one exists.

func (*Context) String

func (c *Context) String(code int, format string, values ...interface{})

String responses http request by returning plain text

type Engine

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

Engine is the core of Umeshu. It contains the mux, middlewares, session manager and view render. Use New() or Default() to create it.

func Default

func Default() *Engine

Default returns an Engine instance with Recovery middleware already attached. Internally, it calls (*Engine).New() and attaches Recovery middleware.

func New

func New() *Engine

New returns a new blank Engine instance without any middleware attached. It is also act as the first routerGroup with empty prefix.

func (Engine) Any

func (g Engine) Any(pattern string, handler HandlerFunc)

Any registers a route that matches all the HTTP methods, i.e. GET, POST, PUT, PATCH, HEAD, OPTIONS, DELETE, CONNECT, TRACE.

func (*Engine) ApplyMiddleware

func (e *Engine) ApplyMiddleware()

ApplyMiddleware apply middlewares on all registered routes.

Warning: this function must be invoked before http.Server starts Listening and serving http requests. Otherwise, no middlewares will be attached to routes.

func (Engine) BasePath

func (g Engine) BasePath() string

BasePath returns the base path of routerGroup. For example, if v := (*engine).Group("/v1/api"), v.BasePath() is "/v1/api".

func (Engine) CONNECT

func (g Engine) CONNECT(pattern string, handler HandlerFunc)

CONNECT registers handler for CONNECT request.

func (Engine) DELETE

func (g Engine) DELETE(pattern string, handler HandlerFunc)

DELETE registers handler for DELETE request.

func (*Engine) EnablePprof

func (e *Engine) EnablePprof()

EnablePprof adds pprof related handlers to router. Default index page for debug is "/debug/pprof/"

func (*Engine) EnableSession

func (e *Engine) EnableSession(settings session.SessionSettings)

EnableSession starts session.Manager with settings provided. Use session.DefaultSession for default settings.

func (Engine) GET

func (g Engine) GET(pattern string, handler HandlerFunc)

GET registers handler for GET request.

func (*Engine) Group

func (e *Engine) Group(prefix string) *routerGroup

Group creates a new router group.

func (Engine) HEAD

func (g Engine) HEAD(pattern string, handler HandlerFunc)

HEAD registers handler for HEAD request.

func (*Engine) LoadHTMLTemplates

func (e *Engine) LoadHTMLTemplates(folder string, funcMap FuncMap)

LoadHTMLTemplates loads the templates from folder and stores it in ViewManager, it also stores FuncMap.

func (Engine) OPTIONS

func (g Engine) OPTIONS(pattern string, handler HandlerFunc)

OPTIONS registers handler for OPTIONS request.

func (Engine) PATCH

func (g Engine) PATCH(pattern string, handler HandlerFunc)

PATCH registers handler for PATCH request.

func (Engine) POST

func (g Engine) POST(pattern string, handler HandlerFunc)

POST registers handler for POST request.

func (Engine) PUT

func (g Engine) PUT(pattern string, handler HandlerFunc)

PUT registers handler for PUT request.

func (*Engine) Run

func (e *Engine) Run(addr string)

Run sets up a http server and starts listening and serving HTTP requests.

func (*Engine) RunTLS

func (e *Engine) RunTLS(addr, certFile, keyFile string)

Run sets up a http server and starts listening and serving HTTPS requests.

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(rw http.ResponseWriter, r *http.Request)

ServeHTTP conforms to http.Handler interface.

func (*Engine) Shutdown

func (e *Engine) Shutdown()

Shutdown sends a message to http.Server to shut it down.

func (Engine) Static

func (g Engine) Static(pattern string, root string)

Static serves static files from the given file system root

For example:

pattern: /static
root: ./assets

routerGroup prefix will automatically applied if it is place under routerGroup or sub-routerGroup route parameters will be stored in "filepath".

Use (*Context).GetRouteParam("filepath") to get the value.

func (Engine) SubGroup

func (g Engine) SubGroup(prefix string) *routerGroup

SubGroup creates new sub-routerGroup.

func (Engine) SubGroupWithHander

func (g Engine) SubGroupWithHander(prefix string, method HTTPMethodType, handler HandlerFunc) *routerGroup

SubGroupWithHander creates new sub-routerGroup and defines handler for the sub-routerGroup pattern, i.e. SubGroupWithHander("/v1", umeshu.HTTP_GET, handlerFunc) defining a "/v1" sub-routerGroup - "example.com/v1" and the corresponding handlerFunc for "example.com/v1".

func (Engine) TRACE

func (g Engine) TRACE(pattern string, handler HandlerFunc)

TRACE registers handler for TRACE request.

func (Engine) Use

func (g Engine) Use(middlewares ...HandlerFunc)

Use attaches middlewares to the router group.

type FuncMap

type FuncMap map[string]interface{}

FuncMap is a wrapper of map[string]interface{}, it use to pass FuncMap to HTML template render.

type HTTPMethodType

type HTTPMethodType int
const (
	HTTP_GET HTTPMethodType = iota
	HTTP_HEAD
	HTTP_POST
	HTTP_PUT
	HTTP_DELETE
	HTTP_TRACE
	HTTP_OPTIONS
	HTTP_CONNECT
	HTTP_PATCH
)

type HandlerFunc

type HandlerFunc func(*Context)

HandlerFunc defines the request handler.

func AllocsHandler

func AllocsHandler() HandlerFunc

AllocsHandler will pass the call from /debug/pprof/allocs to pprof.

func BlockHandler

func BlockHandler() HandlerFunc

BlockHandler will pass the call from /debug/pprof/block to pprof.

func CmdlineHandler

func CmdlineHandler() HandlerFunc

CmdlineHandler will pass the call from /debug/pprof/cmdline to pprof.

func GoroutineHandler

func GoroutineHandler() HandlerFunc

GoroutineHandler will pass the call from /debug/pprof/goroutine to pprof.

func HeapHandler

func HeapHandler() HandlerFunc

HeapHandler will pass the call from /debug/pprof/heap to pprof.

func IndexHandler

func IndexHandler() HandlerFunc

IndexHandler will pass the call from /debug/pprof to pprof.

func Logging

func Logging() HandlerFunc

Logging logs the time used for responsing a http request

func MutexHandler

func MutexHandler() HandlerFunc

MutexHandler will pass the call from /debug/pprof/mutex to pprof.

func ProfileHandler

func ProfileHandler() HandlerFunc

ProfileHandler will pass the call from /debug/pprof/profile to pprof.

func Recovery

func Recovery() HandlerFunc

Recovery is a middleware to recover umeshu engine from panic error and provides log for tracing.

func SymbolHandler

func SymbolHandler() HandlerFunc

SymbolHandler will pass the call from /debug/pprof/symbol to pprof.

func ThreadCreateHandler

func ThreadCreateHandler() HandlerFunc

ThreadCreateHandler will pass the call from /debug/pprof/threadcreate to pprof.

func TraceHandler

func TraceHandler() HandlerFunc

TraceHandler will pass the call from /debug/pprof/trace to pprof.

type JSONData

type JSONData map[string]interface{}

JSONData is a map[string]interface{}.

type RouteInfo

type RouteInfo struct {
	Method  string
	Pattern string
}

RouteInfo contains information of a registered route like method and pattern.

type Router

type Router interface {
	// contains filtered or unexported methods
}

Router is a multiplexer. It registers, directs and handles url path.

var GlobalRouter Router = NewRouter()

GlobalRouter is the router instance shared by all routerGroup.

func NewRouter

func NewRouter() Router

NewRouter returns an new router instance

type RouterNode

type RouterNode interface {
	// Find searchs the path and returns registered pattern
	Find(path string) (pattern string)

	// Insert adds new pattern to router node
	Insert(pattern string)
}

RouterNode is the basis unit of a router tree.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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