wits

package module
v0.0.0-...-82862be Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2023 License: MIT Imports: 36 Imported by: 0

README

wits

一个简易的web框架

主要功能包括

路由匹配(前缀树),上下文,拦截器,过滤器 认证(basic,jwt) 数据绑定,响应(json,jsonp,xml,string,重定向,html)支持https

支持中间件扩展 全局中间件以及路由级别中间件,提供 跨域中间件 、访问日志中间件、异常恢复中间件、请求耗时中间件

生命周期扩展机制

统一的异常处理

统一响应设置

cookie session的支持

IP黑白名单设置

路径参数支持 /api/getId/:id

优雅停机

请求超时中间件

配置文件 支持 yaml toml properties

环境变量,支持方便获取参数变量,操作系统变量,配置文件变量

banner打印

快速使用


func main() {
    engine := wits.Default()
    group := engine.Group("api")
    group.GET("probe", func (ctx *wits.Context) {
        _ = ctx.Success(timeutil.Now())
    })
    engine.RunServer()
}


        .__  __          
__  _  _|__|/  |_  ______
\ \/ \/ /  \   __\/  ___/
 \     /|  ||  |  \___ \ 
  \/\_/ |__||__| /____  >
                      \/ 1.0.0
Hello, Welcome To Use Wits.

[WITS] 2023-08-20 17:05:48 /Users/wendell/GolandProjects/shura/wits/utils.go:40 WARN The port is not set and no environment variables app.server.address or app.server.port are configured. 
[WITS] 2023-08-20 17:05:48 /Users/wendell/GolandProjects/shura/wits/utils.go:41 DEBUG The App will Running Listen Address is :8888 Get by default. 

web容器engine常用api

RegisterWarmupFunc      预热
RegisterPostNewFunc     New之后执行
RegisterPreRunFunc      Run之前执行
SetHandlerBizError      统一异常处理
RegisterOnShutdown      优雅停机钩子
ServerPostProcessor     http.server创建后执行
SetLogger               自定义日志
Use                     注册全局中间件
AppName                 获取app名字
AddFilter               全局过滤器
InitAclNodeList // engine.InitAclNodeList("./file/acl.conf") 黑白名单
Group // engine.Group("user") 添加一个路由组
LoadHTMLGlob            加载模版

RunServer               启动
RunTLS                  https启动

上下文Context 常用api

Shutdown() 
GetSessionId()
Cookie(name string)
// 参数绑定
BindXml(obj any)
BindJson(obj any)
// 响应
JSONP(code int, obj any)
Redirect(status int, url string)
JSON(status int, data any)
PureJSON(status int, data any)
ExpandJSON(status int, data any)
ExpandAndPureJSON(status int, data any)
XML(status int, data any)
ExpandXML(status int, data any)
String(status int, format string, values ...any)
HTMLTemplate(code int, name string, obj any) error
Back(code int, msg string)
Success(msg string)
Fail(msg string)
File(filepath string)
FileFromFS(filepath string, fs http.FileSystem)
FileAttachment(filepath, filename string)

Query(key string)
QueryOrDefault(key, defaultValue string)
QueryMap(key string)
PostForm(key string)
PostFormMap(key string)
PostFormArray(key string)
FormFile(name string)
MultipartForm()
BodyMap()
Body(key string)


DEBUG(msg any, data ...any)
INFO(msg any, data ...any)
WARM(msg any, data ...any)
ERROR(msg any, data ...any)

UserAgent()
Referer()
RemoteIP()
ClientIP()
ContentType()
GetMethod()
GetPath()


黑名名单配置

engine.InitAclNodeList("./file/acl.conf")

::1
127.0.0.1
192.168.0.0/16

静态资源服务

group.Static("/static/**", "./file")

路径参数

group.GET("/refresh/:cacheName", func(ctx *wits.Context) {
		cacheName := ctx.GetString("cacheName")
		ctx.String(http.StatusOK, "ok")
})

优雅停机

kill -15 pid

中间件

全局中间件

userGroup.Use(mock.TestMiddleWare)

路由级别
group.GET("probe", func(ctx *wits.Context) {
    _ = ctx.Success(timeutil.Now())
}, func(handlerFunc wits.HandlerFunc) wits.HandlerFunc {
    return func(ctx *wits.Context) {
}
})

全局异常处理

engine.SetHandlerBizError(BizHandler{})

认证

engine.AddFilter(mock.Accounts.BasicAuth())

文件处理

userGroup.GET("file", func(c *wits.Context) {
		c.File("./file/file.xlsx")
})

userGroup.GET("fileFromFS", func(c *wits.Context) {
    c.FileFromFS("file.xlsx", http.Dir("./file"))
})

userGroup.GET("fileAttachment", func(c *wits.Context) {
    c.FileAttachment("./file/下载.txt", "下载.txt")
})

模版

templateMust := template.Must(template.New("t").Parse(`Hello {{.name}}`))
engine.SetHTMLTemplate(templateMust)
userGroup.GET("template1", func(c *wits.Context) {
    c.HTMLTemplate(http.StatusCreated, "t", wits.Map{"name": "wendell"})
})


// ------------
engine.Delims("[{{", "}}]")
engine.SetFuncMap(template.FuncMap{
    "formatAsDate": formatAsDate,
})
engine.LoadHTMLGlob("file/**")

userGroup.GET("template2", func(c *wits.Context) {
    c.HTMLTemplate(http.StatusOK, "hello.tmpl", wits.Map{"name": "world"})

})

参数绑定

func(c *wits.Context) {
    u := &User{}
    err := c.BindJSON(u)
    if err != nil {
        c.ERROR(err.Error())
    }
    c.DEBUG(u)
    _ = c.Success("success")
}

超时设置

  1. 配置方式 app.server.global.timeout.enable=true app.server.global.timeout=5000
  2. 手动开启方式 EnableGlobalTimeout()

session

  1. 配置 app.session.enable = true
  2. 手动 EnableSession()

主要配置

app.session.enable
app.session.id
app.session.store
app.session.filter.Include
app.session.filter.Exclude
app.session.cookie.path
app.session.cookie.maxAge
app.session.cookie.domain
app.session.cookie.secure
app.session.cookie.httponly

RestResult返回

app.rest.result.enable

curl 127.0.0.1:8888/api/probe
{"code":200,"msg":"OK","data":"2023-08-20 17:55:19"}

Documentation

Overview

Package wits 路由路径参数

Index

Constants

View Source
const (
	AuthKey      = "Authorization"
	DefaultRealm = "Require"
	BasicPrefix  = "Basic "
	UserKey      = "UserKey"

	AuthErrorMsg = "AuthErrorMsg"
	JWTToken     = "JWTToken"
	Bearer       = "Bearer "
	RS256        = "RS256"
	RS512        = "RS512"
	RS384        = "RS384"
	HS256        = "HS256"
	HS384        = "HS384"
	HS512        = "HS512"

	WWWAuthenticate = "WWW-Authenticate"
	XRealIP         = "X-Real-Ip"
	XForwardedFor   = "X-Forwarded-For"
	XRequestID      = "X-Request-Id"

	DefaultLogPrefix    = "WITS"
	AppLogPrefix        = "app.log.prefix"
	AppServerCorsEnable = "app.server.cors.enable"
	AppName             = "app.name"
	AppPort             = "app.server.port"
	AppAddress          = "app.server.address"

	AppSessionIdName         = "app.session.id"
	AppSessionEnable         = "app.session.enable"
	AppSessionTimeout        = "app.session.timeout"
	AppSessionStore          = "app.session.store"
	AppSessionFilterInclude  = "app.session.filter.Include"
	AppSessionFilterExclude  = "app.session.filter.Exclude"
	AppSessionCookiePath     = "app.session.cookie.path"
	AppSessionCookieMaxAge   = "app.session.cookie.maxAge"
	AppSessionCookieDomain   = "app.session.cookie.domain"
	AppSessionCookieSecure   = "app.session.cookie.secure"
	AppSessionCookieHttpOnly = "app.session.cookie.httponly"
	AppRestResultEnable      = "app.rest.result.enable"
	AppRecordCostEnable      = "app.server.cost.enable"
	AppGlobalTimeoutEnable   = "app.server.global.timeout.enable"
	AppGlobalTimeout         = "app.server.global.timeout"
	AppBannerEnable          = "app.banner.enable"
)
View Source
const (
	DebugLevel = logger.DebugLevel

	InfoLevel  = logger.InfoLevel
	WarnLevel  = logger.WarnLevel
	ErrorLevel = logger.ErrorLevel
	TEXT       = logger.TEXT
)
View Source
const ANY = "ANY"

Variables

View Source
var DefaultAuthCheckHandler = func(ctx *Context) {
	msg := ctx.GetString(AuthErrorMsg)
	if msg == "" {
		msg = "Authorization failure"
	}
	_ = ctx.String(http.StatusUnauthorized, msg)

}
View Source
var GlobalTimeout time.Duration
View Source
var (
	IdName string
)
View Source
var RequestLog = &Filter{
	Order:   1,
	Include: "/**",
	BeforeFunc: func(ctx *Context) bool {
		ctx.DEBUG("received new connect clientIp: %s,method: %s, path: %s", logger.Blue(ctx.RemoteIP()), logger.Blue(ctx.GetMethod()), logger.Blue(ctx.R.URL.Path))
		return true
	},
}

Functions

func BasicAuth

func BasicAuth(username, password string) string

BasicAuth base64处理

func CreateTestContext

func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine)

func Debug

func Debug(msg any, a ...any)

func EnableGlobalTimeout

func EnableGlobalTimeout()

EnableGlobalTimeout 手动开启全局超时

func EnableSession

func EnableSession()

EnableSession 应用手动开启

func Error

func Error(msg any, a ...any)

func Fatal

func Fatal(msg any, a ...any)

func Get

func Get(pattern string) (value any, err error)

func GetAddress

func GetAddress() string

func GetAll

func GetAll() (data map[string]any, err error)

func GetAppName

func GetAppName() string

func GetArray

func GetArray(pattern string) (value []any)

func GetBool

func GetBool(pattern string, def ...bool) (value bool)

func GetInt

func GetInt(pattern string, def ...int) (value int)

func GetInt64

func GetInt64(pattern string, def ...int64) (value int64)

func GetLogPrefix

func GetLogPrefix() string

func GetPort

func GetPort() string

func GetString

func GetString(pattern string, def ...string) (value string)

func GetStringMap

func GetStringMap(pattern string) (value map[string]any)

func GetTime

func GetTime(pattern string, def ...time.Duration) (value time.Duration)

func Info

func Info(msg any, a ...any)

func IsOpenCors

func IsOpenCors() bool

IsOpenCors 是否打开跨域 开发阶段打开

func NewSessionManager

func NewSessionManager(ttl int, store string)

NewSessionManager 如果是手动开启session EnableSession 那么也应该设置session的相应参数 ttl 超时时间,store 存储方式

func RefreshToken

func RefreshToken(token string, date time.Duration, key []byte) (string, error)

RefreshToken 刷新令牌 token 令牌 date 续期时间

func RestResultEnable

func RestResultEnable() bool

func SetBanner

func SetBanner(b string)

func SetCookie

func SetCookie(name, value string, ctx *Context, options ...*CookieOptions)

func SetCtx

func SetCtx(ctx context.Context)

func SetGlobalTimeout

func SetGlobalTimeout(timeout time.Duration)

SetGlobalTimeout 设置全局超时 毫秒

func SetLog

func SetLog(l *logger.Logger)

func Text

func Text(msg any, a ...any)

func Warn

func Warn(msg any, a ...any)

func WrapPost

func WrapPost(response response.Response)

func WrapPre

func WrapPre(response response.Response)

WrapPre {"code":200,"msg":"ok","data":""}

Types

type Accounts

type Accounts struct {
	UnAuthHandler AuthCheckHandler
	Users         map[string]string
}

func (*Accounts) BasicAuth

func (a *Accounts) BasicAuth() *Filter

BasicAuth 过滤器 返回一个过滤器 将过滤器添加到engine即可使用

type AuthCheckHandler

type AuthCheckHandler func(ctx *Context)

AuthCheckHandler 定义一个没有认证的回调 DefaultAuthCheckHandler 默认回调 Accounts 逻辑完全由业务自己定义 业务将user加载到Accounts对象 业务设置没有检查到user的处理逻辑

type CommonHandler

type CommonHandler struct {
}

func (*CommonHandler) HandlerError

func (handler *CommonHandler) HandlerError(ctx *Context, err *goerr.BizError)

type Context

type Context struct {
	W response.Response

	R *http.Request
	// contains filtered or unexported fields
}

func (*Context) Back

func (c *Context) Back(code int, msg string) error

func (*Context) BindJSON

func (c *Context) BindJSON(obj any) error

BindJSON curl -X POST -d '{"name":"wendell","age":28}' http://127.0.0.1:8888/user/bind/json

func (*Context) BindXml

func (c *Context) BindXml(obj any) error

BindXml

@Example

type User struct {
		Name string `xml:"name"`
		Age  int    `xml:"age"`
}

curl -X POST -d '<?xml version="1.0" encoding="UTF-8"?><root><age>25</age><name>juan</name></root>' -H 'Content-Type: application/xml' http://127.0.0.1:8888/user/bind/xml

func (*Context) Body

func (c *Context) Body(key string) (v any)

func (*Context) BodyMap

func (c *Context) BodyMap() map[string]any

func (*Context) ByteToString

func (c *Context) ByteToString(status int, data []byte) error

func (*Context) ClientIP

func (c *Context) ClientIP() string

func (*Context) ContentType

func (c *Context) ContentType() string

func (*Context) Cookie

func (c *Context) Cookie(name string) (string, error)

Cookie 查找cookie

func (*Context) Copy

func (c *Context) Copy() *Context

Copy 拷贝上下文为一个新对象 由于context是一个资源复用的对象 如果业务使用携程需要拷贝一份copy

func (*Context) Ctx

func (c *Context) Ctx() context.Context

func (*Context) DEBUG

func (c *Context) DEBUG(msg any, data ...any)

DEBUG INFO ERROR 日志打印 **************************提供框架使用框架日志打印方法start*****************************

func (*Context) DisableDecoderUseNumber

func (c *Context) DisableDecoderUseNumber(fun func())

func (*Context) DisableStrictMatching

func (c *Context) DisableStrictMatching(fun func())

func (*Context) ERROR

func (c *Context) ERROR(msg any, data ...any)

func (*Context) EnableDecoderUseNumber

func (c *Context) EnableDecoderUseNumber(fun func())

func (*Context) EnableStrictMatching

func (c *Context) EnableStrictMatching(fun func())

func (*Context) ExpandAndPureJSON

func (c *Context) ExpandAndPureJSON(status int, data any) error

func (*Context) ExpandJSON

func (c *Context) ExpandJSON(status int, data any) error

ExpandJSON 是否展开json

func (*Context) ExpandXML

func (c *Context) ExpandXML(status int, data any) error

func (*Context) Fail

func (c *Context) Fail(msg string) error

func (*Context) File

func (c *Context) File(filepath string)

File 文件操作

func (*Context) FileAttachment

func (c *Context) FileAttachment(filepath, filename string)

func (*Context) FileFromFS

func (c *Context) FileFromFS(filepath string, fs http.FileSystem)

func (*Context) FormFile

func (c *Context) FormFile(name string) (*multipart.FileHeader, error)

FormFile 返回第一个文件,一般业务就使用这一个 如果有多个文件可以使用 MultipartForm

func (*Context) Get

func (c *Context) Get(key string) (value any, exists bool)

func (*Context) GetBody

func (c *Context) GetBody(key string) (v any, ok bool)

func (*Context) GetBool

func (c *Context) GetBool(key string) (b bool)

func (*Context) GetDuration

func (c *Context) GetDuration(key string) (d time.Duration)

func (*Context) GetFloat64

func (c *Context) GetFloat64(key string) (f64 float64)

func (*Context) GetHandlerBizError

func (c *Context) GetHandlerBizError() HandlerBizError

func (*Context) GetInt

func (c *Context) GetInt(key string) (i int)

func (*Context) GetInt64

func (c *Context) GetInt64(key string) (i64 int64)

func (*Context) GetMethod

func (c *Context) GetMethod() string

func (*Context) GetPath

func (c *Context) GetPath() string

func (*Context) GetPostForm

func (c *Context) GetPostForm(key string) (string, bool)

func (*Context) GetPostFormArray

func (c *Context) GetPostFormArray(key string) (values []string, ok bool)

func (*Context) GetPostFormMap

func (c *Context) GetPostFormMap(key string) (map[string]string, bool)

func (*Context) GetQuery

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

GetQuery 一般来说一个key对应一个参数,是大部分业务所需求的

func (*Context) GetQueryArray

func (c *Context) GetQueryArray(key string) (values []string, ok bool)

GetQueryArray url.Values 是一个 map[string][]string 所以同一个key可以有多个值 提供一个获取数组的方法

func (*Context) GetQueryMap

func (c *Context) GetQueryMap(key string) (map[string]string, bool)

func (*Context) GetSessionId

func (c *Context) GetSessionId() string

GetSessionId 需要开启session支持

func (*Context) GetString

func (c *Context) GetString(key string) (s string)

func (*Context) GetStringMap

func (c *Context) GetStringMap(key string) (sm map[string]any)

func (*Context) GetStringMapString

func (c *Context) GetStringMapString(key string) (sms map[string]string)

func (*Context) GetStringMapStringSlice

func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)

func (*Context) GetStringSlice

func (c *Context) GetStringSlice(key string) (ss []string)

func (*Context) GetTime

func (c *Context) GetTime(key string) (t time.Time)

func (*Context) GetUint

func (c *Context) GetUint(key string) (ui uint)

func (*Context) GetUint64

func (c *Context) GetUint64(key string) (ui64 uint64)

func (*Context) GetUser

func (c *Context) GetUser() string

func (*Context) HTMLTemplate

func (c *Context) HTMLTemplate(code int, name string, obj any) error

func (*Context) HandlerError

func (c *Context) HandlerError(err *goerr.BizError)

HandlerError SetHandlerBizError GetHandlerBizError Panic *****************************业务异常处理start***************************************

func (*Context) Header

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

func (*Context) INFO

func (c *Context) INFO(msg any, data ...any)

func (*Context) JSON

func (c *Context) JSON(status int, data any) error

func (*Context) JSONP

func (c *Context) JSONP(code int, obj any)

func (*Context) MultipartForm

func (c *Context) MultipartForm() (*multipart.Form, error)

MultipartForm 通过 Form.file 拿到多个文件,是一个map对象

func (*Context) MustBindWith

func (c *Context) MustBindWith(obj any, b bind.Bind) error

func (*Context) MustGet

func (c *Context) MustGet(key string) any

func (*Context) NewSession

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

NewSession 创建一个session 一般只给登录请求使用,并且需要开启session支持 app.session.enable

func (*Context) Panic

func (c *Context) Panic(msg string)

func (*Context) PostForm

func (c *Context) PostForm(key string) (value string)

PostForm application/x-www-form-urlencoded curl -X POST -d "sex=女&person[weight]=148&person[hight]=1.75" http://127.0.0.1:8888/user/add

func (*Context) PostFormArray

func (c *Context) PostFormArray(key string) (values []string)

func (*Context) PostFormMap

func (c *Context) PostFormMap(key string) (dicts map[string]string)

func (*Context) PureJSON

func (c *Context) PureJSON(status int, data any) error

PureJSON 带有html格式的json不被编码

func (*Context) Query

func (c *Context) Query(key string) (value string)

Query 绝大部分业务不想处理bool,希望框架返回一个值就行啦 curl http://127.0.0.1:8888/user/add\?id=1001\&person%5Bname%5D=wendell\&person%5Bage%5D=21

func (*Context) QueryArray

func (c *Context) QueryArray(key string) (values []string)

QueryArray 业务不需要ok bool参数

func (*Context) QueryMap

func (c *Context) QueryMap(key string) (dicts map[string]string)

QueryMap

请求 curl 127.0.0.1:8888/user/person[name]=wendell&person[age]=21 需要返回

{
	"name":"wendell"
	"age": 21
}

func (*Context) QueryOrDefault

func (c *Context) QueryOrDefault(key, defaultValue string) (value string)

QueryOrDefault 带有默认值的返回,不需要业务再去判空

func (*Context) Redirect

func (c *Context) Redirect(status int, url string) error

func (*Context) Referer

func (c *Context) Referer() string

func (*Context) RemoteIP

func (c *Context) RemoteIP() string

RemoteIP 获取客户端ip

func (*Context) Render

func (c *Context) Render(status int, r render.Render) error

func (*Context) RequestHeader

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

RequestHeader *************头部操作***************************

func (*Context) Reset

func (c *Context) Reset(w http.ResponseWriter, r *http.Request)

Reset 由于使用了对象池资源复用,复用的时候需要清理上一次缓存的数据

func (*Context) ReturnNow

func (c *Context) ReturnNow(status int)

func (*Context) SaveUploadedFile

func (c *Context) SaveUploadedFile(file *multipart.FileHeader, dst string) error

SaveUploadedFile 拿到文件后可以上传到指定的目录

func (*Context) Session

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

func (*Context) Set

func (c *Context) Set(key string, value any)

func (*Context) SetCookie

func (c *Context) SetCookie(name, value string, options ...*CookieOptions)

SetCookie 添加cookie到响应头

func (*Context) SetHandlerBizError

func (c *Context) SetHandlerBizError(handler HandlerBizError)

func (*Context) SetSameSite

func (c *Context) SetSameSite(samesite http.SameSite)

SetSameSite with cookie SameSiteDefaultMode SameSite = iota + 1

SameSiteLaxMode
SameSiteStrictMode
SameSiteNoneMode

*****************************cookie start***************************************

func (*Context) ShouldBindWith

func (c *Context) ShouldBindWith(obj any, b bind.Bind) error

func (*Context) Shutdown

func (c *Context) Shutdown()

func (*Context) String

func (c *Context) String(status int, format string, values ...any) error

func (*Context) Success

func (c *Context) Success(msg string) error

func (*Context) UserAgent

func (c *Context) UserAgent() string

func (*Context) WARN

func (c *Context) WARN(msg any, data ...any)

func (*Context) XML

func (c *Context) XML(status int, data any) error

type CookieOptions

type CookieOptions struct {
	MaxAge           time.Duration
	Path, Domain     string
	Secure, HttpOnly bool
}

CookieOptions 可选项

func GetCookieOptionsByEnv

func GetCookieOptionsByEnv() *CookieOptions

type Engine

type Engine struct {
	FuncMap template.FuncMap

	// form表单上传文件的读取是是否全部加载到内存的阈值
	MaxMultipartMemory int64

	// 需要在应用启动的时候执行
	PreRunFunc []func()

	// New出一个Engine的时候执行
	PostNewFunc []func()

	// 应用启动完后的预热操作
	WarmupFunc []func()
	// contains filtered or unexported fields
}

func Default

func Default() *Engine

Default 一般情况下使用默认的便可满足需求

func New

func New() *Engine

New 得到一个全新Engine 执行 engine.Run() 即可启动一个web服务

func (*Engine) AddFilter

func (e *Engine) AddFilter(check *Filter)

AddFilter 添加过滤器

func (*Engine) AppName

func (e *Engine) AppName() string

AppName web服务名称

func (*Engine) Delims

func (e *Engine) Delims(left, right string) *Engine

Delims 模版规则一般默认是{{xx}} engine.Delims("[{{", "}}]")

func (*Engine) GetAcl

func (e *Engine) GetAcl() acl.Acl

func (Engine) Group

func (r Engine) Group(name string) *routerGroup

func (*Engine) InitAclNodeList

func (e *Engine) InitAclNodeList(fileName string)

InitAclNodeList 初始化白名单列表 例如:fileName 文件名 ./file/acl.conf

func (*Engine) LoadHTMLFiles

func (e *Engine) LoadHTMLFiles(files ...string)

func (*Engine) LoadHTMLGlob

func (e *Engine) LoadHTMLGlob(pattern string)

LoadHTMLGlob 根据pattern规则一次性初始化多个模版 例如 file/**

func (*Engine) Logger

func (e *Engine) Logger() *logger.Logger

func (*Engine) RegisterOnShutdown

func (e *Engine) RegisterOnShutdown(hook func())

func (*Engine) RegisterPostNewFunc

func (e *Engine) RegisterPostNewFunc(postNew func())

RegisterPostNewFunc New 之后执行

func (*Engine) RegisterPreRunFunc

func (e *Engine) RegisterPreRunFunc(preRun func())

RegisterPreRunFunc 添加启动函数 Run 之前执行

func (*Engine) RegisterWarmupFunc

func (e *Engine) RegisterWarmupFunc(warmup func())

RegisterWarmupFunc 添加预热执行函数

func (*Engine) RegistryServerPostProcessor

func (e *Engine) RegistryServerPostProcessor(processor ServerPostProcessor)

func (*Engine) Run

func (e *Engine) Run(address ...string)

Run 启动一个web服务 ⚠️ 没有预热操作

func (*Engine) RunServer

func (e *Engine) RunServer(address ...string)

RunServer 建议都是用该函数启动 初始化 预热 优雅停机

func (*Engine) RunTLS

func (e *Engine) RunTLS(certFile, keyFile string, address ...string) (err error)

RunTLS 支持https启动 ⚠️ 没有预热操作

func (*Engine) ServeHTTP

func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request)
type Handler interface {
	ServeHTTP(ResponseWriter, *Request)
}

ServeHTTP 实现Handler接口,是的Engine本身就是一个请求执行函数 目的是为了实现统一的入口 /** -> Engine

func (*Engine) SetAcl

func (e *Engine) SetAcl(acl acl.Acl)

SetAcl 设置防火墙

func (*Engine) SetFuncMap

func (e *Engine) SetFuncMap(funcMap template.FuncMap)

SetFuncMap FuncMap

func formatAsDate(t time.Time) string {
	year, month, day := t.Date()
	return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}
engine.SetFuncMap(template.FuncMap{
		"formatAsDate": formatAsDate,
})

func (*Engine) SetHTMLTemplate

func (e *Engine) SetHTMLTemplate(template *template.Template)

SetHTMLTemplate 初始化模版

func (*Engine) SetHandlerBizError

func (e *Engine) SetHandlerBizError(handler HandlerBizError)

SetHandlerBizError 设置异常处理函数

func (*Engine) SetLogger

func (e *Engine) SetLogger(logger *logger.Logger)

SetLogger 替换日志

func (*Engine) SetRouterHandler

func (e *Engine) SetRouterHandler(handler RouterHandler)

SetRouterHandler 注册路由处理函数 只有当需要做一些其他中间件的时候可能用到

func (*Engine) Shutdown

func (e *Engine) Shutdown()

Shutdown 发送终止信号

func (*Engine) Use

func (e *Engine) Use(middlewares ...MiddlewareFunc)

Use 全局路由

func (Engine) UseFront

func (r Engine) UseFront(middlewares ...MiddlewareFunc)

func (*Engine) Warmup

func (e *Engine) Warmup()

Warmup 预热操作

type Filter

type Filter struct {
	Order   int    // 排序,order较小的优先执行
	Include string // 路径匹配,匹配到的才会执行 BeforeFunc and AfterFunc
	Exclude string // 排除某个路径,即使include包含也不会执行

	BeforeFunc func(ctx *Context) bool
	AfterFunc  func(ctx *Context)
	// contains filtered or unexported fields
}

Filter 过滤器 在接收到请求执行beforeFunc 请求完成之后执行afterFunc

func IpCheck

func IpCheck(IsBlock ...bool) *Filter

func (Filter) Chain

func (r Filter) Chain(handler func(ctx *Context)) func(ctx *Context)

Chain 实现beforeFunc先执行的afterFunc应该后执行

type FilterChain

type FilterChain []*Filter

func (FilterChain) Len

func (r FilterChain) Len() int

func (FilterChain) Less

func (r FilterChain) Less(i, j int) bool

Less 比较,将order大的排到前面,实际上是最后执行

func (FilterChain) Swap

func (r FilterChain) Swap(i, j int)

type HandlerBizError

type HandlerBizError interface {
	HandlerError(ctx *Context, err *goerr.BizError)
}

type HandlerFunc

type HandlerFunc func(ctx *Context)

func Recovery

func Recovery(next HandlerFunc) HandlerFunc

type JwtAuth

type JwtAuth struct {
	UnAuthHandler AuthCheckHandler
	Include       string
	Exclude       string
	//key
	Key []byte
}

func (*JwtAuth) Auth

func (j *JwtAuth) Auth() *Filter

func (*JwtAuth) ParseToken

func (j *JwtAuth) ParseToken(token string, ctx *Context) *jwt.Token

type JwtToken

type JwtToken struct {
	Key     []byte
	TimeOut time.Duration
	Alg     string
	GetData func(ctx *Context) (map[string]any, error)
}

func (*JwtToken) GetToken

func (j *JwtToken) GetToken() MiddlewareFunc

GetToken 获取token,是一个前置中间件 应该使用在某一个路由中,比如/login 其中提供一个获取数据的函数,以获得数据生成token

type Map

type Map map[string]any

type MiddlewareFunc

type MiddlewareFunc func(handlerFunc HandlerFunc) HandlerFunc

func Timeout

func Timeout(t ...time.Duration) MiddlewareFunc

Timeout 超时中间件 timeout 毫秒

type NothingHandler

type NothingHandler struct {
}

func (NothingHandler) HandlerError

func (biz NothingHandler) HandlerError(ctx *Context, err *goerr.BizError)

type Response

type Response struct {
	Writer http.ResponseWriter

	Committed bool
	// contains filtered or unexported fields
}

func Wrap

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

func (*Response) Buffer

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

func (*Response) BufferString

func (r *Response) BufferString() string

func (*Response) ClearBuffer

func (r *Response) ClearBuffer()

func (*Response) ContentType

func (r *Response) ContentType() string

func (*Response) Flush

func (r *Response) Flush()

func (*Response) Header

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

func (*Response) Hijack

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

func (*Response) Reset

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

func (*Response) SetHeader

func (r *Response) SetHeader(name, value string)

func (*Response) Size

func (r *Response) Size() int64

func (*Response) Status

func (r *Response) Status() int

func (*Response) Unwrap

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

func (*Response) Write

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

func (*Response) WriteHeader

func (r *Response) WriteHeader(status int)

func (*Response) WriteStatus

func (r *Response) WriteStatus(status int)

func (*Response) WriteStatusNow

func (r *Response) WriteStatusNow()

func (*Response) WriteString

func (r *Response) WriteString(s string) (n int, err error)

type RestResult

type RestResult struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
	Data any    `json:"data"`
}

RestResult 统一返回结果 {"code":200,"msg":"ok","data":""} 一般来说code 200 表示正常,其他表示异常

type RouterHandler

type RouterHandler func(ctx *Context)

RouterHandler 路由的真正处理逻辑,不同的逻辑可以实现不同的功能,例如代理转发

type ServerPostProcessor

type ServerPostProcessor func(*http.Server)

ServerPostProcessor Server的扩展

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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