dotweb package - github.com/devfeel/dotweb - Go Packages

View Source

const (
	LogTarget_Default        = "dotweb_default"
	LogTarget_HttpRequest    = "dotweb_request"
	LogTarget_HttpServer     = "dotweb_server"
	LogTarget_RequestTimeout = "dotweb_req_timeout"

	LogLevel_Debug = "debug"
	LogLevel_Info  = "info"
	LogLevel_Warn  = "warn"
	LogLevel_Error = "error"
)

Log define

View Source

const (
	CharsetUTF8       = "charset=utf-8"
	DefaultServerName = "dotweb"
)

Http define

View Source

const (
	Windows = "windows"
	Linux   = "linux"
)

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 (
	HeaderContentDisposition            = "Content-Disposition"
	HeaderContentEncoding               = "Content-Encoding"
	HeaderContentLength                 = "Content-Length"
	HeaderContentType                   = "Content-Type"

	
	HeaderXContentTypeOptions     = "X-Content-Type-Options"
	HeaderContentSecurityPolicy   = "Content-Security-Policy"
)

Headers

View Source

const (

	
	ItemKeyHandleStartTime = "dotweb.HttpContext.StartTime"
	
	ItemKeyHandleDuration = "dotweb.HttpContext.HandleDuration"
)

View Source

const (
	
	DefaultHTTPPort = 8080

	DefaultLogPath = ""

	
	RunMode_Development = "development"
	
	RunMode_Production = "production"

	
	StartMode_New = "New"
	
	StartMode_Classic = "Classic"
)

View Source

const (
	RouteMethod_Any       = "ANY"
	RouteMethod_GET       = "GET"
	RouteMethod_HEAD      = "HEAD"
	RouteMethod_OPTIONS   = "OPTIONS"
	RouteMethod_POST      = "POST"
	RouteMethod_PUT       = "PUT"
	RouteMethod_PATCH     = "PATCH"
	RouteMethod_DELETE    = "DELETE"
	RouteMethod_HiJack    = "HIJACK"
	RouteMethod_WebSocket = "WEBSOCKET"
)

View Source

const (
	DefaultGzipLevel = 9

	DefaultIndexPage = "index.html"
)

Global define

func DefaultAutoOPTIONSHandler

func DefaultAutoOPTIONSHandler(ctx Context) error

DefaultAutoOPTIONSHandler default handler for options request if set HttpServer.EnabledAutoOPTIONS, auto bind this handler Sets CORS headers to support cross-origin preflight requests (Issue #250)

func DefaultUniqueIDGenerater() string

DefaultUniqueIDGenerater default generater used to create Unique Id

func HTTPNotFound(ctx Context)

HTTPNotFound simple notfound function for Context

func NewRouter(server *HttpServer) *router

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

type BaseMiddleware struct {
	
}

BaseMiddleware is the base struct, user defined middleware should extend this

func (bm *BaseMiddleware) Exclude(routers ...string)

Exclude Exclude this middleware with router

ExistsExcludeRouter check is exists router in exclude map

func (bm *BaseMiddleware) HasExclude() bool

HasExclude check has set exclude router

func (bm *BaseMiddleware) SetNext(m Middleware)
type BaseMiddlware struct {
	BaseMiddleware
}

BaseMiddlware is a shortcut for BaseMiddleware Deprecated: 由于该struct命名有误,将在2.0版本弃用,请大家尽快修改自己的middleware

type Binder interface {
	Bind(interface{}, Context) error
	BindJsonBody(interface{}, Context) error
}

Binder is the interface that wraps the Bind method.

type Context interface {
	Context() context.Context
	SetTimeoutContext(timeout time.Duration) context.Context
	WithContext(runCtx context.Context)
	HttpServer() *HttpServer
	Response() *Response
	Request() *Request
	WebSocket() *WebSocket
	HijackConn() *HijackConn
	RouterNode() RouterNode
	RouterParams() Params
	Handler() HttpHandle
	Tools() *Tools
	AppItems() core.ConcurrenceMap
	Cache() cache.Cache
	Items() core.ConcurrenceMap
	ConfigSet() core.ReadonlyMap
	ViewData() core.ConcurrenceMap
	SessionID() string
	Session() (state *session.SessionState)
	DestorySession() error
	Hijack() (*HijackConn, error)
	IsHijack() bool
	IsWebSocket() bool
	End()
	IsEnd() bool
	Redirect(code int, targetUrl string) error
	QueryString(key string) string
	QueryInt(key string) int
	QueryInt64(key string) int64
	FormValue(key string) string
	PostFormValue(key string) string
	File(file string) (err error)
	Attachment(file string, name string) error
	Inline(file string, name string) error
	Bind(i interface{}) error
	BindJsonBody(i interface{}) error
	
	Validate(i interface{}) error
	GetRouterName(key string) string
	RemoteIP() string
	SetCookieValue(name, value string, maxAge int)
	SetCookie(cookie *http.Cookie)
	RemoveCookie(name string)
	ReadCookieValue(name string) (string, error)
	ReadCookie(name string) (*http.Cookie, error)
	AddView(name ...string) []string
	View(name string) error
	ViewC(code int, name string) error
	Write(code int, content []byte) (int, error)
	WriteString(contents ...interface{}) error
	WriteStringC(code int, contents ...interface{}) error
	WriteHtml(contents ...interface{}) error
	WriteHtmlC(code int, contents ...interface{}) error
	WriteBlob(contentType string, b []byte) error
	WriteBlobC(code int, contentType string, b []byte) error
	WriteJson(i interface{}) error
	WriteJsonC(code int, i interface{}) error
	WriteJsonBlob(b []byte) error
	WriteJsonBlobC(code int, b []byte) error
	WriteJsonp(callback string, i interface{}) error
	WriteJsonpBlob(callback string, b []byte) error
	
}
type ContextCreater func() Context

Classic create and return DotApp instance\ if set logPath = "", it will use bin-root/logs for log-root 1.SetEnabledLog(true) 2.use RequestLog Middleware 3.print logo

ClassicWithConf create and return DotApp instance must set config info

New create and return DotApp instance default run mode is RunMode_Production

Cache return cache interface

Close immediately stops the server. It internally calls `http.Server#Close()`.

func (app *DotWeb) ExcludeUse(m Middleware, routers ...string)

ExcludeUse registers a middleware exclude routers like exclude /index or /query/:id

GetMiddlewareFunc get middleware with given name

func (app *DotWeb) GlobalUniqueID() string

GlobalUniqueID return app's GlobalUniqueID it will be Initializationed when StartServer

func (app *DotWeb) IncludeDotwebGroup()

IncludeDotwebGroup init inner routers which start with /dotweb/

func (app *DotWeb) IsDevelopmentMode() bool

IsDevelopmentMode check current run mode is development mode

func (*DotWeb) ListenAndServe

ListenAndServe start server with addr not support pprof server auto start

Logger return app's logger

func (app *DotWeb) MustStart()

MustStart start app server with set config If an exception occurs, will be panic it if no set Server.Port, will be use DefaultHttpPort

ReSetConfig reset config for app only apply when app is running Port can not be modify if EnabledPProf, EnabledPProf flag and PProfPort can not be modify

func (app *DotWeb) RegisterMiddlewareFunc(name string, middleFunc MiddlewareFunc)

RegisterMiddlewareFunc register middleware with given name & middleware

RunMode current app run mode, if not set, default set RunMode_Development

SetCache set cache interface

SetConfig set config for app

func (app *DotWeb) SetDevelopmentMode()

SetDevelopmentMode set run mode on development mode 1.SetEnabledLog(true) 2.SetEnabledConsole(true)

func (app *DotWeb) SetEnabledLog(enabledLog bool)

SetEnabledLog set enabled log flag

func (*DotWeb) SetExceptionHandle

func (app *DotWeb) SetExceptionHandle(handler ExceptionHandle)

SetExceptionHandle set custom error handler

func (app *DotWeb) SetLogPath(path string)

SetLogPath set log root path

SetLogger set user logger, the logger must implement logger.AppLog interface

func (*DotWeb) SetMethodNotAllowedHandle

func (app *DotWeb) SetMethodNotAllowedHandle(handler StandardHandle)

SetMethodNotAllowedHandle set custom 405 handler

func (app *DotWeb) SetMock(mock Mock)

SetMock set mock logic

func (*DotWeb) SetNotFoundHandle

func (app *DotWeb) SetNotFoundHandle(handler StandardHandle)

SetNotFoundHandle set custom 404 handler

func (app *DotWeb) SetPProfConfig(enabledPProf bool, httpport int)

SetPProfConfig set pprofserver config, default is disable and don't use same port with StartServer

func (app *DotWeb) SetProductionMode()

SetProductionMode set run mode on production mode

Shutdown stops server gracefully. It internally calls `http.Server#Shutdown()`.

Start start app server with set config If an exception occurs, will be return it if no set Server.Port, will be use DefaultHttpPort

func (app *DotWeb) StartServer(httpPort int) error

StartServer start server with http port if config the pprof, will be start pprof server

StateInfo return app's ServerStateInfo

func (app *DotWeb) Use(m ...Middleware)

Use registers middlewares

func (app *DotWeb) UsePlugin(plugins ...Plugin)

UsePlugin registers plugins

func (app *DotWeb) UseRequestLog()

UseRequestLog register RequestLogMiddleware

UseTimeoutHook register TimeoutHookMiddleware

type Group interface {
	
	Use(m ...Middleware) Group
	
	Group(prefix string, m ...Middleware) Group
	
	DELETE(path string, h HttpHandle) RouterNode
	
	GET(path string, h HttpHandle) RouterNode
	
	HEAD(path string, h HttpHandle) RouterNode
	
	OPTIONS(path string, h HttpHandle) RouterNode
	
	PATCH(path string, h HttpHandle) RouterNode
	
	POST(path string, h HttpHandle) RouterNode
	
	PUT(path string, h HttpHandle) RouterNode
	
	ServerFile(path string, fileroot string) RouterNode
	
	RegisterRoute(method, path string, h HttpHandle) RouterNode
	
	SetNotFoundHandle(handler StandardHandle) Group
}

Group is the interface that wraps the group router methods. A Group allows you to create routes with a common prefix and middleware chain.

func NewGroup(prefix string, server *HttpServer) Group

hijack conn

func (hj *HijackConn) SetHeader(key, value string)

SetHeader hjiack conn write header

WriteBlob hjiack conn write []byte

WriteString hjiack conn write string

type HttpContext struct {
	
}

AddView add need parse views before View()

AppContext get application's global appcontext issue #3

Attachment sends a response as attachment, prompting client to save the file. for issue #39

func (ctx *HttpContext) Bind(i interface{}) error

Bind decode req.Body or form-value to struct

func (*HttpContext) BindJsonBody

func (ctx *HttpContext) BindJsonBody(i interface{}) error

BindJsonBody default use json decode req.Body to struct

Cache get application's global cache

ConfigSet get appset from config file update for issue #16 Config file

Context return context.Context

func (ctx *HttpContext) DestorySession() error

DestorySession delete all contents of the session and set the sessionId to empty

func (ctx *HttpContext) End()

End set context user handler process end if set HttpContext.End,ignore user handler, but exec all http module - fixed issue #5

File sends a response with the content of the file if file not exists, response 404 for issue #39

FormValue returns the first value for the named component of the query. POST and PUT body parameters take precedence over URL query string values.

GetRouterName get router name

func (*HttpContext) Handler

func (ctx *HttpContext) Handler() HttpHandle

Hijack make current connection to hijack mode

func (ctx *HttpContext) HijackConn() *HijackConn
func (ctx *HttpContext) HttpServer() *HttpServer

HttpServer return HttpServer

Inline sends a response as inline, opening the file in the browser. if file not exists, response 404 for issue #39

func (ctx *HttpContext) IsHijack() bool
func (ctx *HttpContext) IsWebSocket() bool

Items get request's item context lazy init when first use

PostFormValue returns the first value for the named component of the POST, PATCH, or PUT request body. URL query parameters are ignored.

QueryInt get query key with int format if not exists or not int type, return 0

QueryInt64 get query key with int64 format if not exists or not int64 type, return 0

QueryString returns request parameters according to key

ReadCookie read cookie object for name

ReadCookieValue read cookie value for name

Redirect replies to the request with a redirect to url and with httpcode default you can use http.StatusFound

RemoteIP return user IP address

func (ctx *HttpContext) RemoveCookie(name string)

RemoveCookie remove cookie for path&name

func (ctx *HttpContext) Request() *Request
func (ctx *HttpContext) Response() *Response
func (ctx *HttpContext) RouterNode() RouterNode
func (ctx *HttpContext) RouterParams() Params

Session get session state in current context

SetCookie write cookie with cookie-obj

func (ctx *HttpContext) SetCookieValue(name, value string, maxAge int)

SetCookieValue write cookie for name & value & maxAge default path = "/" default domain = current domain default maxAge = 0 // seconds seconds=0 means no 'Max-Age' attribute specified. seconds<0 means delete cookie now, equivalently 'Max-Age: 0' seconds>0 means Max-Age attribute present and given in seconds

SetTimeoutContext set new Timeout Context set Context & cancle withvalue RequestID

func (ctx *HttpContext) Tools() *Tools

Tools get tools lazy init when first use

func (ctx *HttpContext) Validate(i interface{}) error

Validate validates data with HttpServer::Validator We will implementing inner validator on next version

View write view content to response

ViewC write (httpCode, view content) to response

ViewData get view data context lazy init when first use

func (ctx *HttpContext) WebSocket() *WebSocket

WithContext set Context with RequestID

Write write code and content content to response

WriteBlob write []byte content to response

WriteBlobC write (httpCode, []byte) to response

func (ctx *HttpContext) WriteHtml(contents ...interface{}) error

WriteString write (200, string, text/html) to response

func (ctx *HttpContext) WriteHtmlC(code int, contents ...interface{}) error

WriteHtmlC write (httpCode, string, text/html) to response

func (ctx *HttpContext) WriteJson(i interface{}) error

WriteJson write (httpCode, json string) to response auto convert interface{} to json string

WriteJsonBlob write json []byte to response

WriteJsonBlobC write (httpCode, json []byte) to response

func (ctx *HttpContext) WriteJsonC(code int, i interface{}) error

WriteJsonC write (httpCode, json string) to response auto convert interface{} to json string

func (ctx *HttpContext) WriteJsonp(callback string, i interface{}) error

WriteJsonp write jsonp string to response

WriteJsonpBlob write jsonp string as []byte to response

func (ctx *HttpContext) WriteString(contents ...interface{}) error

WriteString write (200, string, text/plain) to response

func (ctx *HttpContext) WriteStringC(code int, contents ...interface{}) error

WriteStringC write (httpCode, string, text/plain) to response

type HttpHandle

HttpHandle is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a special parameter Context contain all request and response data.

type HttpModule struct {
	Name string
	
	OnBeginRequest func(Context)
	
	OnEndRequest func(Context)
}

HttpModule global module in http server it will be no effect when websocket request or use offline mode

type HttpServer struct {
	Modules   []*HttpModule
	DotApp    *DotWeb
	Validator Validator
	
}
func NewHttpServer() *HttpServer
func (server *HttpServer) Any(path string, handle HttpHandle)

ANY is a shortcut for router.Handle("Any", path, handle) it support GET\HEAD\POST\PUT\PATCH\OPTIONS\DELETE

func (server *HttpServer) Binder() Binder

Binder get binder interface in server

func (server *HttpServer) DELETE(path string, handle HttpHandle) RouterNode

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

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

GetSessionManager get session manager in current httpserver

Group create new group with current HttpServer

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

func (server *HttpServer) HiJack(path string, handle HttpHandle)

HiJack is a shortcut for router.HiJack(path, handle)

IndexPage default index page name

func (server *HttpServer) InitSessionManager()

InitSessionManager init session manager

func (server *HttpServer) IsOffline() bool

IsOffline check server is set offline state

func (*HttpServer) ListenAndServe

ListenAndServe listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming connections.

func (*HttpServer) ListenAndServeTLS

ListenAndServeTLS listens on the TCP network address srv.Addr and then calls Serve to handle requests on incoming TLS connections. Accepted connections are configured to enable TCP keep-alives.

Filenames containing a certificate and matching private key for the server must be provided if neither the Server's TLSConfig.Certificates nor TLSConfig.GetCertificate are populated. If the certificate is signed by a certificate authority, the certFile should be the concatenation of the server's certificate, any intermediates, and the CA's certificate.

If srv.Addr is blank, ":https" is used.

ListenAndServeTLS always returns a non-nil error.

Logger is a shortcut for dotweb.Logger

func (server *HttpServer) OPTIONS(path string, handle HttpHandle) RouterNode

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

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

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

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

func (*HttpServer) RegisterHandlerFunc added in v1.7.5

RegisterHandlerFunc a shortcut for router.RegisterHandlerFunc(routeMethod string, path string, handler http.HandlerFunc)

func (server *HttpServer) RegisterModule(module *HttpModule)

RegisterModule add HttpModule

RegisterRoute a shortcut for router.RegisterRoute(routeMethod string, path string,handle HttpHandle)

RegisterServerFile a shortcut for router.RegisterServerFile(routeMethod, path, fileRoot) simple demo:server.RegisterServerFile(RouteMethod_GET, "/src/*", "/var/www", nil) simple demo:server.RegisterServerFile(RouteMethod_GET, "/src/*filepath", "/var/www", []string{".zip", ".rar"})

func (server *HttpServer) Renderer() Renderer

Renderer get renderer interface in server if no set, init InnerRenderer

func (server *HttpServer) Router() Router

Router get router interface in server

ServeHTTP make sure request can be handled correctly

ServerConfig a shortcut for App.Config.ServerConfig

ServerFile a shortcut for router.ServeFiles(path, fileRoot) simple demo:server.ServerFile("/src/*filepath", "/var/www")

SessionConfig a shortcut for App.Config.SessionConfig

func (server *HttpServer) SetBinder(binder Binder)

SetBinder set custom Binder on HttpServer

func (server *HttpServer) SetContextCreater(creater ContextCreater)

SetContextCreater

func (server *HttpServer) SetEnabledAutoHEAD(isEnabled bool)

SetEnabledAutoHEAD set route use auto head set EnabledAutoHEAD true or false default is false

func (server *HttpServer) SetEnabledAutoOPTIONS(isEnabled bool)

SetEnabledAutoOPTIONS set route use auto options set SetEnabledAutoOPTIONS true or false default is false

func (server *HttpServer) SetEnabledBindUseJsonTag(isEnabled bool)

SetEnabledBindUseJsonTag set whethr to enable json tab on Bind, default is false

func (server *HttpServer) SetEnabledDetailRequestData(isEnabled bool)

SetEnabledDetailRequestData 设置是否启用详细请求数据统计,默认为false

func (server *HttpServer) SetEnabledGzip(isEnabled bool)

SetEnabledGzip set whether to enable gzip, default is false

func (server *HttpServer) SetEnabledIgnoreFavicon(isEnabled bool)

SetEnabledIgnoreFavicon set IgnoreFavicon Enabled default is false

func (server *HttpServer) SetEnabledListDir(isEnabled bool)

SetEnabledListDir set whether to allow listing of directories, default is false

func (server *HttpServer) SetEnabledRequestID(isEnabled bool)

SetEnabledRequestID set create unique request id per request set EnabledRequestID true or false default is false

func (server *HttpServer) SetEnabledSession(isEnabled bool)

SetEnabledSession set whether to enable session, default is false

func (server *HttpServer) SetEnabledStaticFileMiddleware(isEnabled bool)

SetEnabledStaticFileMiddleware set flag which enabled or disabled middleware for static-file route

func (server *HttpServer) SetEnabledTLS(isEnabled bool, certFile, keyFile string)

SetEnabledTLS set tls enabled default is false if it's true, must input certificate\private key fileName

func (server *HttpServer) SetIdleTimeout(idleTimeout int64)

SetIdleTimeout IdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled with Millisecond

func (server *HttpServer) SetIndexPage(indexPage string)

SetIndexPage set default index page name

func (*HttpServer) SetMaxBodySize added in v1.7.3

func (server *HttpServer) SetMaxBodySize(maxBodySize int64)

SetMaxBodySize set body size to limit read

SetOffline set server offline config

func (server *HttpServer) SetReadHeaderTimeout(readHeaderTimeout int64)

SetReadHeaderTimeout ReadHeaderTimeout is the amount of time allowed to read request headers with Millisecond

func (server *HttpServer) SetReadTimeout(readTimeout int64)

SetReadTimeout To limit the request's body size to be read with Millisecond

func (server *HttpServer) SetRenderer(r Renderer)

SetRenderer set custom renderer in server

SetSessionConfig set session store config

func (server *HttpServer) SetVirtualPath(path string)

SetVirtualPath set current server's VirtualPath

func (server *HttpServer) SetWriteTimeout(writeTimeout int64)

SetWriteTimeout WriteTimeout is the maximum duration before timing out writes of the response with Millisecond

StateInfo is a shortcut for dotweb.StateInfo

func (server *HttpServer) VirtualPath() string

VirtualPath return current server's VirtualPath

func (server *HttpServer) WebSocket(path string, handle HttpHandle)

WebSocket is a shortcut for router.WebSocket(path, handle)

IdGenerater the handler for create Unique Id default is use dotweb.

type Middleware interface {
	Handle(ctx Context) error
	SetNext(m Middleware)
	Next(ctx Context) error
	Exclude(routers ...string)
	HasExclude() bool
	ExistsExcludeRouter(router string) bool
}

middleware execution priority: app > group > router Middleware middleware interface

type MiddlewareFunc func() Middleware
type Mock interface {
	
	Register(route string, handler MockHandle)
	
	RegisterString(route string, resData interface{})
	
	RegisterJSON(route string, resData interface{})
	
	CheckNeedMock(Context) bool
	
	Do(Context)
}

Mock the define Mock module

type MockHandle

type MockHandle func(ctx Context)

MockHandle the handle define on mock module

func (n *Node) AppMiddlewares() []Middleware

AppMiddlewares return AppMiddlewares

func (n *Node) GroupMiddlewares() []Middleware

GroupMiddlewares return GroupMiddlewares

func (n *Node) Middlewares() []Middleware

Middlewares return middlewares

func (n *Node) Node() *Node

Path return full path in node

func (n *Node) Use(m ...Middleware) *Node

Use registers a middleware

func NewDefaultNotifyPlugin(app *DotWeb) *NotifyPlugin

NewDefaultNotifyPlugin return new NotifyPlugin with default config

func (p *NotifyPlugin) IsValidate() bool

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

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.

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.

Plugin a interface for app's global plugin

Renderer is the interface that wraps the render method.

func NewInnerRenderer() Renderer

NewInnerRenderer create a inner renderer instance

func NewInnerRendererNoCache() Renderer

NewInnerRendererNoCache create a inner renderer instance with no cache mode

func (*Request) ContentType

ContentType get ContentType

ExistsQueryKey check is exists from query params with the given key.

FormFile get file by form key

FormFiles get multi files fixed #92

FormValues including both the URL field's query parameters and the POST or PUT form data

func (req *Request) FullRemoteIP() string

FullRemoteIP RemoteAddr to an "IP:port" address

func (req *Request) IsAJAX() bool

IsAJAX returns if it is a ajax request

Path returns requested path.

The path is valid until returning from RequestHandler.

func (*Request) PostBody

func (req *Request) PostBody() []byte

PostBody returns data from the POST or PUT request body

PostString returns the first value for the named component of the POST or PUT request body. URL query parameters are ignored. Deprecated: Use the PostFormValue instead

PostValues contains the parsed form data from POST, PATCH, or PUT body parameters

QueryHeader query header value by key

QueryString returns the first value associated with the given key.

QueryStrings parses RawQuery and returns the corresponding values.

RawQuery returns the original query string

RealIP returns the first ip from 'X-Forwarded-For' or 'X-Real-IP' header key if not exists data, returns request.RemoteAddr fixed for #164

RemoteIP RemoteAddr to an "IP" address

RequestID get unique ID with current request must HttpServer.SetEnabledRequestID(true) default is empty string

type RequestLogMiddleware struct {
	BaseMiddleware
}

func (*RequestLogMiddleware) Handle

type Response struct {
	Status int
	Size   int64
	
}

func (*Response) Body

func (r *Response) Body() []byte

End stop current response

func (r *Response) HttpCode() int

HttpCode return http code format int

func (r *Response) SetHeader(key, val string)

Write writes the data to the connection as part of an HTTP reply.

WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.

type Router interface {
	ServeHTTP(ctx Context)
	ServerFile(path string, fileRoot string) RouterNode
	RegisterServerFile(routeMethod string, path string, fileRoot string, excludeExtension []string) RouterNode
	GET(path string, handle HttpHandle) RouterNode
	HEAD(path string, handle HttpHandle) RouterNode
	OPTIONS(path string, handle HttpHandle) RouterNode
	POST(path string, handle HttpHandle) RouterNode
	PUT(path string, handle HttpHandle) RouterNode
	PATCH(path string, handle HttpHandle) RouterNode
	DELETE(path string, handle HttpHandle) RouterNode
	HiJack(path string, handle HttpHandle)
	WebSocket(path string, handle HttpHandle)
	Any(path string, handle HttpHandle)
	RegisterHandlerFunc(routeMethod string, path string, handler http.HandlerFunc) RouterNode
	RegisterRoute(routeMethod string, path string, handle HttpHandle) RouterNode
	RegisterHandler(name string, handler HttpHandle)
	GetHandler(name string) (HttpHandle, bool)
	MatchPath(ctx Context, routePath string) bool
	GetAllRouterExpress() map[string]struct{}
}

Router is the interface that wraps the router method.

type RouterHandle

type RouterHandle func(ctx Context)

Handle is a function that can be registered to a route to handle HTTP requests. Like http.HandlerFunc, but has a third parameter for the values of wildcards (variables).

type RouterNode interface {
	Use(m ...Middleware) *Node
	AppMiddlewares() []Middleware
	GroupMiddlewares() []Middleware
	Middlewares() []Middleware
	Path() string
	Node() *Node
}

type StandardHandle

type StandardHandle func(Context)

StandardHandle for standard request handling

type StandardMock

type StandardMock struct {
	
}

StandardMock standard mock implement for Mock interface

func NewStandardMock

func NewStandardMock() *StandardMock

NewStandardMock create new StandardMock

func (*StandardMock) CheckNeedMock

func (m *StandardMock) CheckNeedMock(ctx Context) bool

CheckNeedMock check is need do mock logic

func (*StandardMock) Do

func (m *StandardMock) Do(ctx Context)

Do do mock logic

func (*StandardMock) Register

func (m *StandardMock) Register(route string, handler MockHandle)

Register register MockHandle on route

func (*StandardMock) RegisterJSON

func (m *StandardMock) RegisterJSON(route string, resData interface{})

RegisterJSON register return mock json on route

func (*StandardMock) RegisterString

func (m *StandardMock) RegisterString(route string, resData interface{})

RegisterString register return mock string on route

type TimeoutHookMiddleware struct {
	BaseMiddleware
	HookHandle      StandardHandle
	TimeoutDuration time.Duration
}

func (*TimeoutHookMiddleware) Handle

func (t *Tools) PrettyJson(data interface{}) string

FileName get upload file client-local name

GetFileExt get upload file extensions

func (*UploadFile) RandomFileName

RandomFileName get upload file random name with uuid

func (f *UploadFile) ReadBytes() []byte

ReadBytes Bytes returns a slice of byte hoding the UploadFile.File special: if you read bytes, it's will cause empty data in UploadFile.File, so you use SaveFile will no any data to save

SaveFile save file in server-local with filename special: if you SaveFile, it's will cause empty data when use ReadBytes

Size get upload file size

type Validator interface {
	Validate(i interface{}) error
}

Validator is the interface that wraps the Validate function.

type ValueNode struct {
	Params
	Method string
	Node   *Node
}

ReadMessage read message from websocket.conn

SendMessage send message from websocket.conn