dotweb

package module
v1.7.21 Latest Latest
Warning

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

Go to latest
Published: Apr 15, 2023 License: MIT Imports: 42 Imported by: 117

README

DotWeb

Simple and easy go web micro framework

Important: Now need go1.9+ version support, and support go mod.

Document: https://www.kancloud.cn/devfeel/dotweb/346608

Guide: https://github.com/devfeel/dotweb/blob/master/docs/GUIDE.md

Gitter GoDoc Go Report Card Go Build Card Golang-Devfeel

1. Install

go get github.com/devfeel/dotweb

2. Getting Started

package main

import (
	"fmt"
	"github.com/devfeel/dotweb"
)

func main() {
	//init DotApp
	app := dotweb.New()
	//set log path
	app.SetLogPath("/home/logs/wwwroot/")
	//set route
	app.HttpServer.GET("/index", func(ctx dotweb.Context) error{
		return ctx.WriteString("welcome to my first web!")
	})
	//begin server
	fmt.Println("dotweb.StartServer begin")
	err := app.StartServer(80)
	fmt.Println("dotweb.StartServer error => ", err)
}

examples: https://github.com/devfeel/dotweb-example

3. Features

  • 支持go mod
  • 支持静态路由、参数路由、组路由
  • 路由支持文件/目录服务,支持设置是否允许目录浏览
  • HttpModule支持,支持路由之前全局级别的自定义代码能力
  • 中间件支持,支持App、Group、Router级别的设置 - https://github.com/devfeel/middleware
  • Feature支持,可绑定HttpServer全局启用
  • 支持STRING/JSON/JSONP/HTML格式输出
  • 集成Mock能力
  • 支持自定义Context
  • 集成Timeout Hook
  • 全局HTTP错误处理
  • 全局日志处理
  • 支持Hijack与websocket
  • 内建Cache支持
  • 内建Session支持 - 支持主备redis自动切换
  • 内建TLS支持
  • 支持接入第三方模板引擎(需实现dotweb.Renderer接口)
  • 模块可配置
  • 自集成基础统计数据,并支持按分钟为单位的间隔时间统计数据输出
Config Example

4. Performance

DotWeb  1.9.2  16core16G                      
cpu 内存 Samples Average Median 90%Line 95%Line 99%Line Min Max Error% Throughput Received KB/Sec Send KB/Sec
40% 39M 15228356 19 4 43 72 204 0 2070 0.00% 48703.47 7514.79 8656.28
40% 42M 15485189 18 4 41 63 230 0 3250 0.00% 49512.99 7639.7 8800.16
40% 44M 15700385 18 3 41 64 233 0 2083 0.00% 50203.32 7746.22 8922.86
                           
ECHO 1.9.2 16core16G                      
cpu 内存 Samples Average Median 90%Line 95%Line 99%Line Min Max Error% Throughput Received KB/Sec Send KB/Sec
38% 35M 15307586 19 4 44 76 181 0 1808 0.00% 48951.22 6166.71 9034.94
36% 35M 15239058 19 4 45 76 178 0 2003 0.00% 48734.26 6139.37 8994.9
37% 37M 15800585 18 3 41 66 229 0 2355 0.00% 50356.09 6343.68 9294.24
                           
Gin   1.9.2  16core16G                       
cpu 内存 Samples Average Median 90%Line 95%Line 99%Line Min Max Error% Throughput Received KB/Sec Send KB/Sec
36% 36M 15109143 19 6 44 71 175 0 3250 0.00% 48151.87 5877.91 8746.33
36% 40M 15255749 19 5 43 70 189 0 3079 0.00% 48762.53 5952.45 8857.25
36% 40M 15385401 18 4 42 66 227 0 2312 0.00% 49181.03 6003.54 8933.27

5. Router

1) 常规路由
  • 支持GET\POST\HEAD\OPTIONS\PUT\PATCH\DELETE 这几类请求方法
  • 支持HiJack\WebSocket\ServerFile三类特殊应用
  • 支持Any注册方式,默认兼容GET\POST\HEAD\OPTIONS\PUT\PATCH\DELETE方式
  • 支持通过配置开启默认添加HEAD方式
  • 支持注册Handler,以启用配置化
  • 支持检查请求与指定路由是否匹配
Router.GET(path string, handle HttpHandle)
Router.POST(path string, handle HttpHandle)
Router.HEAD(path string, handle HttpHandle)
Router.OPTIONS(path string, handle HttpHandle)
Router.PUT(path string, handle HttpHandle)
Router.PATCH(path string, handle HttpHandle)
Router.DELETE(path string, handle HttpHandle)
Router.HiJack(path string, handle HttpHandle)
Router.WebSocket(path string, handle HttpHandle)
Router.Any(path string, handle HttpHandle)
Router.RegisterRoute(routeMethod string, path string, handle HttpHandle)
Router.RegisterHandler(name string, handler HttpHandle)
Router.GetHandler(name string) (HttpHandle, bool)
Router.MatchPath(ctx Context, routePath string) bool

接受两个参数,一个是URI路径,另一个是 HttpHandle 类型,设定匹配到该路径时执行的方法;

2) static router

静态路由语法就是没有任何参数变量,pattern是一个固定的字符串。

package main

import (
    "github.com/devfeel/dotweb"
)

func main() {
    dotapp := dotweb.New()
    dotapp.HttpServer.GET("/hello", func(ctx dotweb.Context) error{
        return ctx.WriteString("hello world!")
    })
    dotapp.StartServer(80)
}

test: curl http://127.0.0.1/hello

3) parameter router

参数路由以冒号 : 后面跟一个字符串作为参数名称,可以通过 HttpContext的 GetRouterName 方法获取路由参数的值。

package main

import (
    "github.com/devfeel/dotweb"
)

func main() {
    dotapp := dotweb.New()
    dotapp.HttpServer.GET("/hello/:name", func(ctx dotweb.Context) error{
        return ctx.WriteString("hello " + ctx.GetRouterName("name"))
    })
    dotapp.HttpServer.GET("/news/:category/:newsid", func(ctx dotweb.Context) error{
    	category := ctx.GetRouterName("category")
	    newsid := ctx.GetRouterName("newsid")
        return ctx.WriteString("news info: category=" + category + " newsid=" + newsid)
    })
    dotapp.StartServer(80)
}

test:
curl http://127.0.0.1/hello/devfeel
curl http://127.0.0.1/hello/category1/1

4) group router
    g := server.Group("/user")
	g.GET("/", Index)
	g.GET("/profile", Profile)

test:
curl http://127.0.0.1/user
curl http://127.0.0.1/user/profile

6. Binder

  • HttpContext.Bind(interface{})
  • Support data from json、xml、Form
type UserInfo struct {
		UserName string `form:"user"`
		Sex      int    `form:"sex"`
}

func TestBind(ctx dotweb.HttpContext) error{
        user := new(UserInfo)
        if err := ctx.Bind(user); err != nil {
        	 return ctx.WriteString("err => " + err.Error())
        }else{
             return ctx.WriteString("TestBind " + fmt.Sprint(user))
        }
}

7. Middleware

Middleware
app.Use(NewAccessFmtLog("app"))

func InitRoute(server *dotweb.HttpServer) {
	server.GET("/", Index)
	server.GET("/use", Index).Use(NewAccessFmtLog("Router-use"))

	g := server.Group("/group").Use(NewAccessFmtLog("group"))
	g.GET("/", Index)
	g.GET("/use", Index).Use(NewAccessFmtLog("group-use"))
}

type AccessFmtLog struct {
	dotweb.BaseMiddlware
	Index string
}

func (m *AccessFmtLog) Handle(ctx dotweb.Context) error {
	fmt.Println(time.Now(), "[AccessFmtLog ", m.Index, "] begin request -> ", ctx.Request.RequestURI)
	err := m.Next(ctx)
	fmt.Println(time.Now(), "[AccessFmtLog ", m.Index, "] finish request ", err, " -> ", ctx.Request.RequestURI)
	return err
}

func NewAccessFmtLog(index string) *AccessFmtLog {
	return &AccessFmtLog{Index: index}
}

8. Server Config

HttpServer:
  • HttpServer.EnabledSession

    设置是否开启Session支持,目前支持runtime、redis两种模式,默认不开启

  • HttpServer.EnabledGzip

    设置是否开启Gzip支持,默认不开启

  • HttpServer.EnabledListDir

    设置是否启用目录浏览,仅对Router.ServerFile有效,若设置该项,则可以浏览目录文件,默认不开启

  • HttpServer.EnabledAutoHEAD

    设置是否自动启用Head路由,若设置该项,则会为除Websocket\HEAD外所有路由方式默认添加HEAD路由,非开发模式默认不开启

  • HttpServer.EnabledAutoOPTIONS

    设置是否自动启用Options路由,若设置该项,则会为除Websocket\HEAD外所有路由方式默认添加OPTIONS路由,非开发模式默认不开启

  • HttpServer.EnabledIgnoreFavicon

    设置是否忽略Favicon的请求,一般用于接口项目

  • HttpServer.EnabledDetailRequestData

    设置是否启用详细请求数据统计,默认为false,若设置该项,将启用ServerStateInfo中DetailRequestUrlData的统计

  • HttpServer.EnabledTLS

    设置是否启用TLS加密处理

  • HttpServer.EnabledIgnoreFavicon

    设置是否忽略favicon响应,默认为false,若设置该项,将会默认注册内集成的IgnoreFaviconModule,在路由生效前执行

  • HttpServer.EnabledBindUseJsonTag

    设置是否启用json tag生效于Bind接口,默认为false,若设置该项,将会在Bind执行时检查json tag

Run Mode
  • 新增development、production模式
  • 默认development,通过DotWeb.SetDevelopmentMode\DotWeb.SetProductionMode开启相关模式
  • 若设置development模式,未处理异常会输出异常详细信息,同时启用日志开关,同时启用日志console打印,同时自动启用AutoHead&AutoOptions
  • 未来会拓展更多运行模式的配置

9. Exception

500 error
  • Default: 当发生未处理异常时,会根据RunMode向页面输出默认错误信息或者具体异常信息,并返回 500 错误头
  • User-defined: 通过DotServer.SetExceptionHandle(handler *ExceptionHandle)实现自定义异常处理逻辑
type ExceptionHandle func(Context, error)
404 error
  • Default: 当发生404异常时,会默认使用http.NotFound处理
  • User-defined: 通过DotWeb.SetNotFoundHandle(handler NotFoundHandle)实现自定义404处理逻辑
type NotFoundHandle  func(http.ResponseWriter, *http.Request)

Dependency

websocket - golang.org/x/net/websocket
redis - github.com/garyburd/redigo
yaml - gopkg.in/yaml.v2

dependency now managed by go mod.

相关项目

LongWeb

项目简介:http长连接网关服务,提供Websocket及长轮询服务

yulibaozi.com

项目简介:基于dotweb与mapper的一款go的博客程序

Golang-Blog-Server

项目简介:基于dotweb的一款go的Blog(博客)服务端

TokenServer

项目简介:token服务,提供token一致性服务以及相关的全局ID生成服务等

Wechat-token

项目简介:微信Access Token中控服务器,用来统一管理各个公众号的access_token,提供统一的接口进行获取和自动刷新Access Token。

dotweb-start

项目简介:基于dotweb、dotlog、mapper、dottask、cache、database的综合项目模板。

Contact Us

QQ-Group:193409346 - Golang-Devfeel
Gitter:Gitter

Documentation

Index

Constants

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 (
	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"
	HeaderXRequestedWith                = "X-Requested-With"
	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"
	HeaderP3P                           = "P3P"
	HeaderCacheControl                  = "Cache-control"

	// 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 (
	HeaderRequestID    = "d_request_id"
	HeaderResponseTime = "d_response_time"
)
View Source
const (

	// ItemKeyHandleStartTime itemkey name for request handler start time
	ItemKeyHandleStartTime = "dotweb.HttpContext.StartTime"
	// ItemKeyHandleDuration itemkey name for request handler time duration
	ItemKeyHandleDuration = "dotweb.HttpContext.HandleDuration"
)
View Source
const (
	// DefaultHTTPPort default http port; fixed for #70 UPDATE default http port 80 to 8080
	DefaultHTTPPort = 8080

	DefaultLogPath = ""

	// RunMode_Development app runmode in development mode
	RunMode_Development = "development"
	// RunMode_Production app runmode in production mode
	RunMode_Production = "production"

	// StartMode_New app startmode in New mode
	StartMode_New = "New"
	// StartMode_Classic app startmode in Classic mode
	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"
)
View Source
const (
	// Version current version
	Version = "1.7.21"
)

Global define

Variables

View Source
var (
	// ErrValidatorNotRegistered error for not register Validator
	ErrValidatorNotRegistered = errors.New("validator not registered")

	// ErrNotFound error for not found file
	ErrNotFound = errors.New("not found file")
)
View Source
var (
	HttpMethodMap map[string]string
)

Functions

func DefaultAutoOPTIONSHandler

func DefaultAutoOPTIONSHandler(ctx Context) error

DefaultAutoOPTIONSHandler default handler for options request if set HttpServer.EnabledAutoOPTIONS, auto bind this handler

func DefaultMethodNotAllowedHandler

func DefaultMethodNotAllowedHandler(ctx Context)

DefaultMethodNotAllowedHandler default exception handler

func DefaultNotFoundHandler

func DefaultNotFoundHandler(ctx Context)

DefaultNotFoundHandler default exception handler

func DefaultTimeoutHookHandler

func DefaultTimeoutHookHandler(ctx Context)

func DefaultUniqueIDGenerater

func DefaultUniqueIDGenerater() string

DefaultUniqueIDGenerater default generater used to create Unique Id

func HTTPNotFound

func HTTPNotFound(ctx Context)

HTTPNotFound simple notfound function for Context

func NewRouter

func NewRouter(server *HttpServer) *router

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

Types

type BaseMiddleware added in v1.7.2

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

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

func (*BaseMiddleware) Exclude added in v1.7.2

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

Exclude Exclude this middleware with router

func (*BaseMiddleware) ExistsExcludeRouter added in v1.7.2

func (bm *BaseMiddleware) ExistsExcludeRouter(router string) bool

ExistsExcludeRouter check is exists router in exclude map

func (*BaseMiddleware) HasExclude added in v1.7.2

func (bm *BaseMiddleware) HasExclude() bool

HasExclude check has set exclude router

func (*BaseMiddleware) Next added in v1.7.2

func (bm *BaseMiddleware) Next(ctx Context) error

func (*BaseMiddleware) SetNext added in v1.7.2

func (bm *BaseMiddleware) SetNext(m Middleware)

type BaseMiddlware

type BaseMiddlware struct {
	BaseMiddleware
}

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

type Binder

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

Binder is the interface that wraps the Bind method.

type Context

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 validates provided `i`. It is usually called after `Context#Bind()`.
	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
	// contains filtered or unexported methods
}

type ContextCreater added in v1.7.16

type ContextCreater func() Context

type DotWeb

type DotWeb struct {
	HttpServer *HttpServer

	Config                  *config.Config
	Mock                    Mock
	Middlewares             []Middleware
	ExceptionHandler        ExceptionHandle
	NotFoundHandler         StandardHandle // NotFoundHandler supports user defined 404 handler
	MethodNotAllowedHandler StandardHandle // MethodNotAllowedHandler fixed for #64 supports user defined MethodNotAllowed handler
	Items                   core.ConcurrenceMap

	StartMode   string
	IDGenerater IdGenerate
	// contains filtered or unexported fields
}

func Classic

func Classic(logPath string) *DotWeb

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

func ClassicWithConf

func ClassicWithConf(config *config.Config) *DotWeb

ClassicWithConf create and return DotApp instance must set config info

func New

func New() *DotWeb

New create and return DotApp instance default run mode is RunMode_Production

func (*DotWeb) Cache

func (app *DotWeb) Cache() cache.Cache

Cache return cache interface

func (*DotWeb) Close

func (app *DotWeb) Close() error

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

func (*DotWeb) DefaultHTTPErrorHandler

func (app *DotWeb) DefaultHTTPErrorHandler(ctx Context, err error)

DefaultHTTPErrorHandler default exception handler

func (*DotWeb) ExcludeUse

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

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

func (*DotWeb) GetMiddlewareFunc

func (app *DotWeb) GetMiddlewareFunc(name string) (MiddlewareFunc, bool)

GetMiddlewareFunc get middleware with given name

func (*DotWeb) GlobalUniqueID

func (app *DotWeb) GlobalUniqueID() string

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

func (*DotWeb) IncludeDotwebGroup

func (app *DotWeb) IncludeDotwebGroup()

IncludeDotwebGroup init inner routers which start with /dotweb/

func (*DotWeb) IsDevelopmentMode

func (app *DotWeb) IsDevelopmentMode() bool

IsDevelopmentMode check current run mode is development mode

func (*DotWeb) ListenAndServe

func (app *DotWeb) ListenAndServe(addr string) error

ListenAndServe start server with addr not support pprof server auto start

func (*DotWeb) Logger

func (app *DotWeb) Logger() logger.AppLog

Logger return app's logger

func (*DotWeb) MustStart

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

func (*DotWeb) ReSetConfig added in v1.7.2

func (app *DotWeb) ReSetConfig(config *config.Config)

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 (*DotWeb) RegisterMiddlewareFunc

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

RegisterMiddlewareFunc register middleware with given name & middleware

func (*DotWeb) RunMode

func (app *DotWeb) RunMode() string

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

func (*DotWeb) SetCache

func (app *DotWeb) SetCache(ca cache.Cache)

SetCache set cache interface

func (*DotWeb) SetConfig

func (app *DotWeb) SetConfig(config *config.Config)

SetConfig set config for app

func (*DotWeb) SetDevelopmentMode

func (app *DotWeb) SetDevelopmentMode()

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

func (*DotWeb) SetEnabledLog

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 (*DotWeb) SetLogPath

func (app *DotWeb) SetLogPath(path string)

SetLogPath set log root path

func (*DotWeb) SetLogger

func (app *DotWeb) SetLogger(log logger.AppLog)

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 (*DotWeb) SetMock

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 (*DotWeb) SetPProfConfig

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

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

func (*DotWeb) SetProductionMode

func (app *DotWeb) SetProductionMode()

SetProductionMode set run mode on production mode

func (*DotWeb) Shutdown

func (app *DotWeb) Shutdown(ctx context.Context) error

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

func (*DotWeb) Start

func (app *DotWeb) Start() error

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 (*DotWeb) StartServer

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

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

func (*DotWeb) StateInfo

func (app *DotWeb) StateInfo() *core.ServerStateInfo

StateInfo return app's ServerStateInfo

func (*DotWeb) Use

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

Use registers middlewares

func (*DotWeb) UsePlugin added in v1.7.2

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

UsePlugin registers plugins

func (*DotWeb) UseRequestLog

func (app *DotWeb) UseRequestLog()

UseRequestLog register RequestLogMiddleware

func (*DotWeb) UseTimeoutHook

func (app *DotWeb) UseTimeoutHook(handler StandardHandle, timeout time.Duration)

UseTimeoutHook register TimeoutHookMiddleware

type ExceptionHandle

type ExceptionHandle func(Context, error)

ExceptionHandle supports exception handling

type Group

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
}

func NewGroup

func NewGroup(prefix string, server *HttpServer) Group

type HijackConn

type HijackConn struct {
	ReadWriter *bufio.ReadWriter
	Conn       net.Conn
	// contains filtered or unexported fields
}

hijack conn

func (*HijackConn) Close

func (hj *HijackConn) Close() error

Close close hijack conn

func (*HijackConn) SetHeader

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

SetHeader hjiack conn write header

func (*HijackConn) WriteBlob

func (hj *HijackConn) WriteBlob(p []byte) (size int, err error)

WriteBlob hjiack conn write []byte

func (*HijackConn) WriteString

func (hj *HijackConn) WriteString(content string) (int, error)

WriteString hjiack conn write string

type HttpContext

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

func (*HttpContext) AddView

func (ctx *HttpContext) AddView(names ...string) []string

AddView add need parse views before View()

func (*HttpContext) AppItems

func (ctx *HttpContext) AppItems() core.ConcurrenceMap

AppContext get application's global appcontext issue #3

func (*HttpContext) Attachment

func (ctx *HttpContext) Attachment(file, name string) (err error)

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

func (*HttpContext) Bind

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

func (*HttpContext) Cache

func (ctx *HttpContext) Cache() cache.Cache

Cache get application's global cache

func (*HttpContext) ConfigSet

func (ctx *HttpContext) ConfigSet() core.ReadonlyMap

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

func (*HttpContext) Context

func (ctx *HttpContext) Context() context.Context

Context return context.Context

func (*HttpContext) DestorySession added in v1.7.21

func (ctx *HttpContext) DestorySession() error

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

func (*HttpContext) End

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

func (*HttpContext) File

func (ctx *HttpContext) File(file string) (err error)

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

func (*HttpContext) FormValue

func (ctx *HttpContext) FormValue(key string) string

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

func (*HttpContext) GetRouterName

func (ctx *HttpContext) GetRouterName(key string) string

GetRouterName get router name

func (*HttpContext) Handler

func (ctx *HttpContext) Handler() HttpHandle

func (*HttpContext) Hijack

func (ctx *HttpContext) Hijack() (*HijackConn, error)

Hijack make current connection to hijack mode

func (*HttpContext) HijackConn

func (ctx *HttpContext) HijackConn() *HijackConn

func (*HttpContext) HttpServer

func (ctx *HttpContext) HttpServer() *HttpServer

HttpServer return HttpServer

func (*HttpContext) Inline

func (ctx *HttpContext) Inline(file, name string) (err error)

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

func (*HttpContext) IsEnd

func (ctx *HttpContext) IsEnd() bool

func (*HttpContext) IsHijack

func (ctx *HttpContext) IsHijack() bool

func (*HttpContext) IsWebSocket

func (ctx *HttpContext) IsWebSocket() bool

func (*HttpContext) Items

func (ctx *HttpContext) Items() core.ConcurrenceMap

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

func (*HttpContext) PostFormValue

func (ctx *HttpContext) PostFormValue(key string) string

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

func (*HttpContext) QueryInt

func (ctx *HttpContext) QueryInt(key string) int

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

func (*HttpContext) QueryInt64

func (ctx *HttpContext) QueryInt64(key string) int64

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

func (*HttpContext) QueryString

func (ctx *HttpContext) QueryString(key string) string

QueryString returns request parameters according to key

func (*HttpContext) ReadCookie

func (ctx *HttpContext) ReadCookie(name string) (*http.Cookie, error)

ReadCookie read cookie object for name

func (*HttpContext) ReadCookieValue

func (ctx *HttpContext) ReadCookieValue(name string) (string, error)

ReadCookieValue read cookie value for name

func (*HttpContext) Redirect

func (ctx *HttpContext) Redirect(code int, targetUrl string) error

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

func (*HttpContext) RemoteIP

func (ctx *HttpContext) RemoteIP() string

RemoteIP return user IP address

func (*HttpContext) RemoveCookie

func (ctx *HttpContext) RemoveCookie(name string)

RemoveCookie remove cookie for path&name

func (*HttpContext) Request

func (ctx *HttpContext) Request() *Request

func (*HttpContext) Response

func (ctx *HttpContext) Response() *Response

func (*HttpContext) RouterNode

func (ctx *HttpContext) RouterNode() RouterNode

func (*HttpContext) RouterParams

func (ctx *HttpContext) RouterParams() Params

func (*HttpContext) Session

func (ctx *HttpContext) Session() (state *session.SessionState)

Session get session state in current context

func (*HttpContext) SessionID

func (ctx *HttpContext) SessionID() string

func (*HttpContext) SetCookie

func (ctx *HttpContext) SetCookie(cookie *http.Cookie)

SetCookie write cookie with cookie-obj

func (*HttpContext) SetCookieValue

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

func (*HttpContext) SetTimeoutContext

func (ctx *HttpContext) SetTimeoutContext(timeout time.Duration) context.Context

SetTimeoutContext set new Timeout Context set Context & cancle withvalue RequestID

func (*HttpContext) Tools added in v1.7.11

func (ctx *HttpContext) Tools() *Tools

Tools get tools lazy init when first use

func (*HttpContext) Validate

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

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

func (*HttpContext) View

func (ctx *HttpContext) View(name string) error

View write view content to response

func (*HttpContext) ViewC

func (ctx *HttpContext) ViewC(code int, name string) error

ViewC write (httpCode, view content) to response

func (*HttpContext) ViewData

func (ctx *HttpContext) ViewData() core.ConcurrenceMap

ViewData get view data context lazy init when first use

func (*HttpContext) WebSocket

func (ctx *HttpContext) WebSocket() *WebSocket

func (*HttpContext) WithContext

func (ctx *HttpContext) WithContext(runCtx context.Context)

WithContext set Context with RequestID

func (*HttpContext) Write

func (ctx *HttpContext) Write(code int, content []byte) (int, error)

Write write code and content content to response

func (*HttpContext) WriteBlob

func (ctx *HttpContext) WriteBlob(contentType string, b []byte) error

WriteBlob write []byte content to response

func (*HttpContext) WriteBlobC

func (ctx *HttpContext) WriteBlobC(code int, contentType string, b []byte) error

WriteBlobC write (httpCode, []byte) to response

func (*HttpContext) WriteHtml

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

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

func (*HttpContext) WriteHtmlC

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

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

func (*HttpContext) WriteJson

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

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

func (*HttpContext) WriteJsonBlob

func (ctx *HttpContext) WriteJsonBlob(b []byte) error

WriteJsonBlob write json []byte to response

func (*HttpContext) WriteJsonBlobC

func (ctx *HttpContext) WriteJsonBlobC(code int, b []byte) error

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

func (*HttpContext) WriteJsonC

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

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

func (*HttpContext) WriteJsonp

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

WriteJsonp write jsonp string to response

func (*HttpContext) WriteJsonpBlob

func (ctx *HttpContext) WriteJsonpBlob(callback string, b []byte) error

WriteJsonpBlob write jsonp string as []byte to response

func (*HttpContext) WriteString

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

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

func (*HttpContext) WriteStringC

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

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

type HttpHandle

type HttpHandle func(Context) error

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

type HttpModule struct {
	Name string
	// OnBeginRequest is the first event in the execution chain
	OnBeginRequest func(Context)
	// OnEndRequest is the last event in the execution chain
	OnEndRequest func(Context)
}

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

type HttpServer

type HttpServer struct {
	Modules   []*HttpModule
	DotApp    *DotWeb
	Validator Validator
	// contains filtered or unexported fields
}

func NewHttpServer

func NewHttpServer() *HttpServer

func (*HttpServer) Any

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 (*HttpServer) Binder

func (server *HttpServer) Binder() Binder

Binder get binder interface in server

func (*HttpServer) DELETE

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

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

func (*HttpServer) GET

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

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

func (*HttpServer) GetSessionManager

func (server *HttpServer) GetSessionManager() *session.SessionManager

GetSessionManager get session manager in current httpserver

func (*HttpServer) Group

func (server *HttpServer) Group(prefix string) Group

Group create new group with current HttpServer

func (*HttpServer) HEAD

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

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

func (*HttpServer) HiJack

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

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

func (*HttpServer) IndexPage

func (server *HttpServer) IndexPage() string

IndexPage default index page name

func (*HttpServer) InitSessionManager

func (server *HttpServer) InitSessionManager()

InitSessionManager init session manager

func (*HttpServer) IsOffline

func (server *HttpServer) IsOffline() bool

IsOffline check server is set offline state

func (*HttpServer) ListenAndServe

func (server *HttpServer) ListenAndServe(addr string) error

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

func (*HttpServer) ListenAndServeTLS

func (server *HttpServer) ListenAndServeTLS(addr string, certFile, keyFile string) error

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.

func (*HttpServer) Logger

func (server *HttpServer) Logger() logger.AppLog

Logger is a shortcut for dotweb.Logger

func (*HttpServer) OPTIONS

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

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

func (*HttpServer) PATCH

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

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

func (*HttpServer) POST

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

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

func (*HttpServer) PUT

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

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

func (*HttpServer) RegisterHandlerFunc added in v1.7.5

func (server *HttpServer) RegisterHandlerFunc(routeMethod string, path string, handler http.HandlerFunc) RouterNode

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

func (*HttpServer) RegisterModule

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

RegisterModule add HttpModule

func (*HttpServer) RegisterRoute added in v1.7.5

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

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

func (*HttpServer) RegisterServerFile

func (server *HttpServer) RegisterServerFile(routeMethod string, path string, fileRoot string, excludeExtension []string) RouterNode

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 (*HttpServer) Renderer

func (server *HttpServer) Renderer() Renderer

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

func (*HttpServer) Router

func (server *HttpServer) Router() Router

Router get router interface in server

func (*HttpServer) ServeHTTP

func (server *HttpServer) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP make sure request can be handled correctly

func (*HttpServer) ServerConfig

func (server *HttpServer) ServerConfig() *config.ServerNode

ServerConfig a shortcut for App.Config.ServerConfig

func (*HttpServer) ServerFile

func (server *HttpServer) ServerFile(path string, fileRoot string) RouterNode

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

func (*HttpServer) SessionConfig

func (server *HttpServer) SessionConfig() *config.SessionNode

SessionConfig a shortcut for App.Config.SessionConfig

func (*HttpServer) SetBinder

func (server *HttpServer) SetBinder(binder Binder)

SetBinder set custom Binder on HttpServer

func (*HttpServer) SetContextCreater added in v1.7.16

func (server *HttpServer) SetContextCreater(creater ContextCreater)

SetContextCreater

func (*HttpServer) SetEnabledAutoHEAD

func (server *HttpServer) SetEnabledAutoHEAD(isEnabled bool)

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

func (*HttpServer) SetEnabledAutoOPTIONS

func (server *HttpServer) SetEnabledAutoOPTIONS(isEnabled bool)

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

func (*HttpServer) SetEnabledBindUseJsonTag

func (server *HttpServer) SetEnabledBindUseJsonTag(isEnabled bool)

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

func (*HttpServer) SetEnabledDetailRequestData

func (server *HttpServer) SetEnabledDetailRequestData(isEnabled bool)

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

func (*HttpServer) SetEnabledGzip

func (server *HttpServer) SetEnabledGzip(isEnabled bool)

SetEnabledGzip set whether to enable gzip, default is false

func (*HttpServer) SetEnabledIgnoreFavicon

func (server *HttpServer) SetEnabledIgnoreFavicon(isEnabled bool)

SetEnabledIgnoreFavicon set IgnoreFavicon Enabled default is false

func (*HttpServer) SetEnabledListDir

func (server *HttpServer) SetEnabledListDir(isEnabled bool)

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

func (*HttpServer) SetEnabledRequestID

func (server *HttpServer) SetEnabledRequestID(isEnabled bool)

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

func (*HttpServer) SetEnabledSession

func (server *HttpServer) SetEnabledSession(isEnabled bool)

SetEnabledSession set whether to enable session, default is false

func (*HttpServer) SetEnabledStaticFileMiddleware

func (server *HttpServer) SetEnabledStaticFileMiddleware(isEnabled bool)

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

func (*HttpServer) SetEnabledTLS

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 (*HttpServer) SetIdleTimeout added in v1.7.19

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 (*HttpServer) SetIndexPage

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

func (*HttpServer) SetOffline

func (server *HttpServer) SetOffline(offline bool, offlineText string, offlineUrl string)

SetOffline set server offline config

func (*HttpServer) SetReadHeaderTimeout added in v1.7.19

func (server *HttpServer) SetReadHeaderTimeout(readHeaderTimeout int64)

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

func (*HttpServer) SetReadTimeout added in v1.7.19

func (server *HttpServer) SetReadTimeout(readTimeout int64)

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

func (*HttpServer) SetRenderer

func (server *HttpServer) SetRenderer(r Renderer)

SetRenderer set custom renderer in server

func (*HttpServer) SetSessionConfig

func (server *HttpServer) SetSessionConfig(storeConfig *session.StoreConfig)

SetSessionConfig set session store config

func (*HttpServer) SetVirtualPath

func (server *HttpServer) SetVirtualPath(path string)

SetVirtualPath set current server's VirtualPath

func (*HttpServer) SetWriteTimeout added in v1.7.19

func (server *HttpServer) SetWriteTimeout(writeTimeout int64)

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

func (*HttpServer) StateInfo

func (server *HttpServer) StateInfo() *core.ServerStateInfo

StateInfo is a shortcut for dotweb.StateInfo

func (*HttpServer) VirtualPath

func (server *HttpServer) VirtualPath() string

VirtualPath return current server's VirtualPath

func (*HttpServer) WebSocket

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

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

type IdGenerate

type IdGenerate func() string

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

type LogJson

type LogJson struct {
	RequestUrl string
	HttpHeader string
	HttpBody   string
}

type Middleware

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

type MiddlewareFunc func() Middleware

type Mock

type Mock interface {
	// Register register MockHandle on route
	Register(route string, handler MockHandle)
	// RegisterString register return mock string on route
	RegisterString(route string, resData interface{})
	// RegisterJSON register return mock json on route
	RegisterJSON(route string, resData interface{})
	// CheckNeedMock check is need do mock logic
	CheckNeedMock(Context) bool
	// Do do mock logic
	Do(Context)
}

Mock the define Mock module

type MockHandle

type MockHandle func(ctx Context)

MockHandle the handle define on mock module

type Node

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

func (*Node) AppMiddlewares

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

AppMiddlewares return AppMiddlewares

func (*Node) GroupMiddlewares

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

GroupMiddlewares return GroupMiddlewares

func (*Node) Middlewares

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

Middlewares return middlewares

func (*Node) Node

func (n *Node) Node() *Node

func (*Node) Path

func (n *Node) Path() string

Path return full path in node

func (*Node) Use

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

Use registers a middleware

type NotifyPlugin added in v1.7.2

type NotifyPlugin struct {
	Root string

	LoopTime int
	ModTimes map[string]time.Time
	// contains filtered or unexported fields
}

func NewDefaultNotifyPlugin added in v1.7.2

func NewDefaultNotifyPlugin(app *DotWeb) *NotifyPlugin

NewDefaultNotifyPlugin return new NotifyPlugin with default config

func (*NotifyPlugin) IsValidate added in v1.7.2

func (p *NotifyPlugin) IsValidate() bool

func (*NotifyPlugin) Name added in v1.7.2

func (p *NotifyPlugin) Name() string

func (*NotifyPlugin) Run added in v1.7.2

func (p *NotifyPlugin) Run() error

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 Plugin added in v1.7.2

type Plugin interface {
	Name() string
	Run() error
	IsValidate() bool
}

Plugin a interface for app's global plugin

type Renderer

type Renderer interface {
	SetTemplatePath(path string)
	Render(io.Writer, interface{}, Context, ...string) error
	RegisterTemplateFunc(string, interface{})
}

Renderer is the interface that wraps the render method.

func NewInnerRenderer

func NewInnerRenderer() Renderer

NewInnerRenderer create a inner renderer instance

func NewInnerRendererNoCache

func NewInnerRendererNoCache() Renderer

NewInnerRendererNoCache create a inner renderer instance with no cache mode

type Request

type Request struct {
	*http.Request
	// contains filtered or unexported fields
}

func (*Request) ContentType

func (req *Request) ContentType() string

ContentType get ContentType

func (*Request) ExistsQueryKey added in v1.7.10

func (req *Request) ExistsQueryKey(key string) bool

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

func (*Request) FormFile

func (req *Request) FormFile(key string) (*UploadFile, error)

FormFile get file by form key

func (*Request) FormFiles

func (req *Request) FormFiles() (map[string]*UploadFile, error)

FormFiles get multi files fixed #92

func (*Request) FormValues

func (req *Request) FormValues() map[string][]string

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

func (*Request) FullRemoteIP

func (req *Request) FullRemoteIP() string

FullRemoteIP RemoteAddr to an "IP:port" address

func (*Request) IsAJAX

func (req *Request) IsAJAX() bool

IsAJAX returns if it is a ajax request

func (*Request) Path

func (req *Request) Path() string

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

func (*Request) PostString

func (req *Request) PostString(key string) string

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

func (*Request) PostValues

func (req *Request) PostValues() map[string][]string

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

func (*Request) QueryHeader

func (req *Request) QueryHeader(key string) string

QueryHeader query header value by key

func (*Request) QueryString

func (req *Request) QueryString(key string) string

QueryString returns the first value associated with the given key.

func (*Request) QueryStrings

func (req *Request) QueryStrings() url.Values

QueryStrings parses RawQuery and returns the corresponding values.

func (*Request) RawQuery

func (req *Request) RawQuery() string

RawQuery returns the original query string

func (*Request) RealIP

func (req *Request) RealIP() 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

func (*Request) RemoteIP

func (req *Request) RemoteIP() string

RemoteIP RemoteAddr to an "IP" address

func (*Request) RequestID

func (req *Request) RequestID() string

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

func (*Request) Url

func (req *Request) Url() string

Url get request url

type RequestLogMiddleware

type RequestLogMiddleware struct {
	BaseMiddleware
}

func (*RequestLogMiddleware) Handle

func (m *RequestLogMiddleware) Handle(ctx Context) error

type Response

type Response struct {
	Status int
	Size   int64
	// contains filtered or unexported fields
}

func NewResponse

func NewResponse(w http.ResponseWriter) (r *Response)

func (*Response) Body

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

func (*Response) BodyString

func (r *Response) BodyString() string

func (*Response) End

func (r *Response) End()

End stop current response

func (*Response) Flush

func (r *Response) Flush()

Flush implements the http.Flusher interface to allow an HTTP handler to flush buffered data to the client. See http.Flusher(https://golang.org/pkg/net/http/#Flusher)

func (*Response) Header

func (r *Response) Header() http.Header

func (*Response) Hijack

func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the http.Hijacker interface to allow an HTTP handler to take over the connection. See https://golang.org/pkg/net/http/#Hijacker

func (*Response) HttpCode

func (r *Response) HttpCode() int

HttpCode return http code format int

func (*Response) Push

func (r *Response) Push(target string, opts *http.PushOptions) error

Push support http2 Push

func (*Response) QueryHeader

func (r *Response) QueryHeader(key string) string

func (*Response) Redirect

func (r *Response) Redirect(code int, targetUrl string) error

func (*Response) SetContentType

func (r *Response) SetContentType(contenttype string)

func (*Response) SetHeader

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

func (*Response) SetStatusCode

func (r *Response) SetStatusCode(code int) error

func (*Response) SetWriter

func (r *Response) SetWriter(w http.ResponseWriter) *Response

func (*Response) Write

func (r *Response) Write(code int, b []byte) (n int, err error)

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

func (*Response) WriteHeader

func (r *Response) WriteHeader(code int) error

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.

func (*Response) Writer

func (r *Response) Writer() http.ResponseWriter

type Router

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

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 {
	// contains filtered or unexported fields
}

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

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

func (*TimeoutHookMiddleware) Handle

func (m *TimeoutHookMiddleware) Handle(ctx Context) error

type Tools added in v1.7.11

type Tools struct {
}

func (*Tools) PrettyJson added in v1.7.11

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

type UploadFile

type UploadFile struct {
	File   multipart.File
	Header *multipart.FileHeader
	// contains filtered or unexported fields
}

func NewUploadFile

func NewUploadFile(file multipart.File, header *multipart.FileHeader) *UploadFile

func (*UploadFile) FileName

func (f *UploadFile) FileName() string

FileName get upload file client-local name

func (*UploadFile) GetFileExt

func (f *UploadFile) GetFileExt() string

GetFileExt get upload file extensions

func (*UploadFile) RandomFileName

func (f *UploadFile) RandomFileName() string

RandomFileName get upload file random name with uuid

func (*UploadFile) ReadBytes

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

func (*UploadFile) SaveFile

func (f *UploadFile) SaveFile(fileName string) (size int64, err error)

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

func (*UploadFile) Size

func (f *UploadFile) Size() int64

Size get upload file size

type Validator

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

Validator is the interface that wraps the Validate function.

type ValueNode

type ValueNode struct {
	Params
	Method string
	Node   *Node
}

type WebSocket

type WebSocket struct {
	Conn *websocket.Conn
}

func (*WebSocket) ReadMessage

func (ws *WebSocket) ReadMessage() (string, error)

ReadMessage read message from websocket.conn

func (*WebSocket) Request

func (ws *WebSocket) Request() *http.Request

Request get http request

func (*WebSocket) SendMessage

func (ws *WebSocket) SendMessage(msg string) error

SendMessage send message from websocket.conn

Directories

Path Synopsis
framework
redis
Package redisutil, for detailed usage, reference http:// doc.redisfans.com/index.html
Package redisutil, for detailed usage, reference http:// doc.redisfans.com/index.html

Jump to

Keyboard shortcuts

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