Documentation
¶
Overview ¶
Package server web 服务管理
Index ¶
- Constants
- type CTXSanitizer
- type Context
- func (ctx *Context) ClientIP() string
- func (ctx *Context) Critical(status int, v ...interface{}) Responser
- func (ctx *Context) Criticalf(status int, format string, v ...interface{}) Responser
- func (ctx *Context) Error(status int, v ...interface{}) Responser
- func (ctx *Context) Errorf(status int, format string, v ...interface{}) Responser
- func (ctx *Context) Now() time.Time
- func (ctx *Context) ParamID(key string, code int) (int64, Responser)
- func (ctx *Context) ParamInt64(key string, code int) (int64, Responser)
- func (ctx *Context) ParamString(key string, code int) (string, Responser)
- func (ctx *Context) Params() *Params
- func (ctx *Context) ParseTime(layout, value string) (time.Time, error)
- func (ctx *Context) Queries() (*Queries, error)
- func (ctx *Context) QueryObject(v interface{}, code int) Responser
- func (ctx *Context) Read(v interface{}, code int) (ok bool)
- func (ctx *Context) Result(code int, fields content.ResultFields) Responser
- func (ctx *Context) ServeFile(p, index string, headers map[string]string) Responser
- func (ctx *Context) ServeFileFS(f fs.FS, p, index string, headers map[string]string) Responser
- func (ctx *Context) Server() *Server
- type Filter
- type HandlerFunc
- type Module
- type ModuleInfo
- type Options
- type Params
- func (p *Params) Bool(key string) bool
- func (p *Params) Errors() content.ResultFields
- func (p *Params) Float64(key string) float64
- func (p *Params) HasErrors() bool
- func (p *Params) ID(key string) int64
- func (p *Params) Int64(key string) int64
- func (p *Params) MustBool(key string, def bool) bool
- func (p *Params) MustFloat64(key string, def float64) float64
- func (p *Params) MustID(key string, def int64) int64
- func (p *Params) MustInt64(key string, def int64) int64
- func (p *Params) MustString(key, def string) string
- func (p *Params) Result(code int) Responser
- func (p *Params) String(key string) string
- type PluginInitFunc
- type Prefix
- func (p *Prefix) Delete(path string, h HandlerFunc) *Prefix
- func (p *Prefix) Get(path string, h HandlerFunc) *Prefix
- func (p *Prefix) Handle(path string, h HandlerFunc, method ...string) error
- func (p *Prefix) Patch(path string, h HandlerFunc) *Prefix
- func (p *Prefix) Post(path string, h HandlerFunc) *Prefix
- func (p *Prefix) Put(path string, h HandlerFunc) *Prefix
- func (p *Prefix) Remove(path string, method ...string)
- type Queries
- func (q *Queries) Bool(key string, def bool) bool
- func (q *Queries) Errors() content.ResultFields
- func (q *Queries) Float64(key string, def float64) float64
- func (q *Queries) HasErrors() bool
- func (q *Queries) Int(key string, def int) int
- func (q *Queries) Int64(key string, def int64) int64
- func (q *Queries) Object(v interface{})
- func (q *Queries) Result(code int) Responser
- func (q *Queries) String(key, def string) string
- type Responser
- type Router
- func (router *Router) Delete(path string, h HandlerFunc) *Router
- func (router *Router) Get(path string, h HandlerFunc) *Router
- func (router *Router) Handle(path string, h HandlerFunc, method ...string) error
- func (router *Router) MuxRouter() *group.Router
- func (router *Router) Patch(path string, h HandlerFunc) *Router
- func (router *Router) Path(pattern string, params map[string]string) (string, error)
- func (router *Router) Post(path string, h HandlerFunc) *Router
- func (router *Router) Prefix(prefix string, filter ...Filter) *Prefix
- func (router *Router) Put(path string, h HandlerFunc) *Router
- func (router *Router) Remove(path string, method ...string)
- func (r *Router) SetDebugger(pprof, vars string) (err error)
- func (router *Router) Static(p, dir, index string) error
- func (router *Router) StaticFS(p string, f fs.FS, index string) error
- func (router *Router) URL(pattern string, params map[string]string) (string, error)
- type Server
- func (srv *Server) AddResult(status, code int, phrase localeutil.Phrase)
- func (srv *Server) AddResults(messages map[int]localeutil.Phrase)
- func (srv *Server) AttachEvent(name string, s Subscriber) (int, error)
- func (srv *Server) Cache() cache.Cache
- func (srv *Server) Close(shutdownTimeout time.Duration) error
- func (srv *Server) DetachEvent(name string, id int)
- func (srv *Server) DisableCompression(disable bool)
- func (srv *Server) Eventer(name string) events.Eventer
- func (srv *Server) Files() *serialization.Files
- func (srv *Server) Locale() *serialization.Locale
- func (srv *Server) LocalePrinter() *message.Printer
- func (srv *Server) Location() *time.Location
- func (srv *Server) Logs() *logs.Logs
- func (srv *Server) Mimetypes() *serialization.Mimetypes
- func (srv *Server) Modules(p *message.Printer) []*ModuleInfo
- func (srv *Server) MuxGroups() *group.Groups
- func (srv *Server) Name() string
- func (srv *Server) NewContext(w http.ResponseWriter, r *http.Request) *Context
- func (srv *Server) NewModule(id, version string, desc localeutil.Phrase, deps ...string) (*Module, error)
- func (srv *Server) NewRouter(name string, root string, matcher group.Matcher, filter ...Filter) (*Router, error)
- func (srv *Server) Now() time.Time
- func (srv *Server) Open(name string) (fs.File, error)
- func (srv *Server) ParseTime(layout, value string) (time.Time, error)
- func (srv *Server) Publisher(name string) events.Publisher
- func (srv *Server) RegisterOnClose(f ...func() error)
- func (srv *Server) RemoveRouter(name string)
- func (srv *Server) Result(p *message.Printer, code int, fields content.ResultFields) content.Result
- func (srv *Server) Results(p *message.Printer) map[int]string
- func (srv *Server) Router(name string) *Router
- func (srv *Server) Serve(tag string, serve bool) (err error)
- func (srv *Server) Services() *service.Manager
- func (srv *Server) SetErrorHandle(h errorhandler.HandleFunc, status ...int)
- func (srv *Server) Tag() language.Tag
- func (srv *Server) Tags() []string
- func (srv *Server) Uptime() time.Time
- func (srv *Server) Vars() *sync.Map
- func (srv *Server) Version() string
- type Subscriber
- type Tag
- func (t *Tag) AddAt(title string, f scheduled.JobFunc, ti time.Time, delay bool) *Tag
- func (t *Tag) AddCron(title string, f scheduled.JobFunc, spec string, delay bool) *Tag
- func (t *Tag) AddInit(title string, f func() error) *Tag
- func (t *Tag) AddJob(title string, f scheduled.JobFunc, scheduler schedulers.Scheduler, delay bool) *Tag
- func (t *Tag) AddRoutes(f func(r *Router), routerName string) *Tag
- func (t *Tag) AddService(title string, f service.Func) *Tag
- func (t *Tag) AddTicker(title string, f scheduled.JobFunc, dur time.Duration, imm, delay bool) *Tag
- func (t *Tag) Inited() bool
- func (t *Tag) Module() *Module
- func (t *Tag) Name() string
- func (t *Tag) Server() *Server
Constants ¶
const PluginInitFuncName = "InitModule"
PluginInitFuncName 插件中的用于获取模块信息的函数名
NOTE: 必须为可导出的函数名称
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CTXSanitizer ¶
type CTXSanitizer interface {
CTXSanitize(*Context) content.ResultFields
}
CTXSanitizer 提供对数据的验证和修正
但凡对象实现了该接口,那么在 Context.Read 和 Queries.Object 中会在解析数据成功之后,调用该接口进行数据验证。
type Context ¶
type Context struct { *content.Context // 与当前对话相关的时区 Location *time.Location // 保存 Context 在存续期间的可复用变量 // // 这是比 context.Value 更经济的传递变量方式。 // // 如果需要在多个请求中传递参数,可直接使用 Server.Vars。 Vars map[interface{}]interface{} // contains filtered or unexported fields }
Context 是对当次 HTTP 请求内容的封装
func NewContext ¶
func NewContext(w http.ResponseWriter, r *http.Request) *Context
NewContext 构建 *Context 实例
func (*Context) ClientIP ¶
ClientIP 返回客户端的 IP 地址
NOTE: 包含了端口部分。
获取顺序如下:
- X-Forwarded-For 的第一个元素
- Remote-Addr 报头
- X-Read-IP 报头
func (*Context) ParamID ¶
ParamID 获取地址参数中表示 key 的值并并转换成大于 0 的 int64
相对于 Context.ParamInt64(),该值必须大于 0。
NOTE: 若需要获取多个参数,使用 Context.Params 会更方便。
func (*Context) ParamInt64 ¶
ParamInt64 取地址参数中的 key 表示的值 int64 类型值
NOTE: 若需要获取多个参数,可以使用 Context.Params 获取会更方便。
func (*Context) ParamString ¶
ParamString 取地址参数中的 key 表示的 string 类型值
NOTE: 若需要获取多个参数,可以使用 Context.Params 获取会更方便。
func (*Context) QueryObject ¶
QueryObject 将查询参数解析到一个对象中
func (*Context) Read ¶
Read 从客户端读取数据并转换成 v 对象
功能与 Unmarshal() 相同,只不过 Read() 在出错时, 会直接调用 Error() 处理:输出 422 的状态码, 并返回一个 false,告知用户转换失败。 如果是数据类型验证失败,则会输出以 code 作为错误代码的错误信息, 并返回 false,作为执行失败的通知。
func (*Context) Result ¶ added in v0.40.0
func (ctx *Context) Result(code int, fields content.ResultFields) Responser
Result 返回 Result 实例
如果找不到 code 对应的错误信息,则会直接 panic。
func (*Context) ServeFileFS ¶
ServeFileFS 提供基于 fs.FS 的文件下载服
type Filter ¶
type Filter func(HandlerFunc) HandlerFunc
Filter 针对 Context 的中间件
Filter 和 github.com/issue9/mux.MiddlewareFunc 本质上没有任何区别, mux.MiddlewareFunc 更加的通用,可以复用市面上的大部分中间件, Filter 则更加灵活一些,适合针对当前框架新的中间件。
如果想要使用 mux.MiddlewareFunc,可以调用 Server.MuxGroups().Middlewares() 方法。
type HandlerFunc ¶
HandlerFunc 路由项处理函数原型
如果返回非空对象,则表示最终向终端输出此内容,不再需要处理其它情况。
func ApplyFilters ¶ added in v0.40.0
func ApplyFilters(next HandlerFunc, filter ...Filter) HandlerFunc
ApplyFilters 将过滤器应用于处理函数 next
type Module ¶
type Module struct {
// contains filtered or unexported fields
}
Module 用于注册初始化模块的相关功能
func (*Module) AddFS ¶ added in v0.41.0
AddFS 将多个文件系统与当前模块的文件系统进行关联
当采用 Module.Open 查找文件时,会根据添加的顺序依次查找文件, 只要存在于某一个文件系统中,那么就当作该文件存在,并返回。
每个模块在初始化时,都会默认将 Server.FS + Module.ID 作为模块的文件系统,通过 AddFS 可以挂载其它的文件系统, 与 embed.FS 相结合,可以做到在外部相对应目录中有修改时, 读取外部的文件,如果不存在,则读取 embed.FS 中的内容。
func (*Module) LoadLocale ¶ added in v0.41.0
LoadLocale 从 m.FS 加载本地化语言文件
type ModuleInfo ¶
type ModuleInfo struct { ID string `yaml:"id" json:"id" xml:"id,attr"` Version string `yaml:"version" json:"version" xml:"version,attr"` Description string `yaml:"description,omitempty" json:"description,omitempty" xml:"description,omitempty"` Deps []string `yaml:"deps,omitempty" json:"deps,omitempty" xml:"dep,omitempty"` }
type Options ¶
type Options struct { // 项目默认可存取的文件系统 // // 默认情况下为可执行文件所在的目录。 FS fs.FS // 服务器的时区 // // 默认值为 time.Local Location *time.Location // 指定生成 Result 数据的方法 // // 默认情况下指向 result.DefaultBuilder。 ResultBuilder content.BuildResultFunc // 缓存系统 // // 默认值为内存类型。 Cache cache.Cache // 端口号 // // 格式参照 net/http.Server.Addr 字段 Port string // 是否禁止自动生成 HEAD 请求 DisableHead bool // 跨域的相关设置 // // 如果为空,采用 mux.DeniedCORS CORS *mux.CORS // 可以对 http.Server 的内容进行修改 // // NOTE: 对 http.Server.Handler 的修改不会启作用,该值始终会指向 Server.groups HTTPServer func(*http.Server) // 在请求崩溃之后的处理方式 // // 这是请求的最后一道防线,如果此函数处理依然 panic,则会造成整个项目退出。 // 如果为空,则会打印简单的错误堆栈信息。 Recovery recovery.RecoverFunc // 此处列出的类型将不会被压缩 // // 可以带 *,比如 text/* 表示所有 mime-type 为 text/ 开始的类型。 IgnoreCompressTypes []string // 日志的输出通道设置 // // 如果此值为空,那么在被初始化 logs.New(nil) 值,表示不会到任务通道,但是各个函数可用。 Logs *logs.Logs // 指定插件的搜索方式 // // 通过 glob 语法搜索插件,比如: // ~/plugins/*.so // 具体可参考:https://golang.org/pkg/path/filepath/#Glob // 为空表示没有插件。 // // 当前仅支持部分系统,具体可查看:https://golang.org/pkg/plugin/ Plugins string // 指定用于处理本地化的方法 // // 可以为空。 Locale *serialization.Locale // 默认的语言标签 // // 在用户请求的报头中没有匹配的语言标签时,会采用此值作为该用户的本地化语言, // 同时也用来初始化 Server.LocalePrinter。 // // 如果为空,则会尝试读取当前系统的本地化信息。 Tag language.Tag // contains filtered or unexported fields }
Options 初始化 Server 的参数
type Params ¶
type Params struct {
// contains filtered or unexported fields
}
Params 用于处理路径中包含的参数
p := ctx.Params() aid := p.Int64("aid") bid := p.Int64("bid") if p.HasErrors() { // do something return }
func (*Params) Bool ¶
Bool 获取参数 key 所代表的值并转换成 bool
最终会调用 strconv.ParseBool 进行转换, 也只有该方法中允许的字符串会被正确转换。
func (*Params) MustBool ¶
MustBool 获取参数 key 所代表的值并转换成 bool
若不存在或是转换出错,则返回 def 作为其默认值。 仅在类型转换出错时,才会向 errors 写入错误信息。
最终会调用 strconv.ParseBool 进行转换, 也只有该方法中允许的字符串会被正确转换。
func (*Params) MustFloat64 ¶
MustFloat64 获取参数 key 所代表的值并转换成 float64
若不存在或是转换出错,则返回 def 作为其默认值。 仅在类型转换出错时,才会向 errors 写入错误信息。
func (*Params) MustID ¶
MustID 获取参数 key 所代表的值并转换成 int64
值必须大于 0,否则会输出错误信息,并返回零值。
若不存在或是转换出错,则返回 def 作为其默认值。 仅在类型转换出错或是小于零时,才会向 errors 写入错误信息。
func (*Params) MustInt64 ¶
MustInt64 获取参数 key 所代表的值并转换成 int64
若不存在或是转换出错,则返回 def 作为其默认值。 仅在类型转换出错时,才会向 errors 写入错误信息。
type PluginInitFunc ¶ added in v0.40.0
PluginInitFunc 安装插件的函数签名
type Prefix ¶
type Prefix struct {
// contains filtered or unexported fields
}
Prefix 带有统一前缀的路由管理
func (*Prefix) Delete ¶
func (p *Prefix) Delete(path string, h HandlerFunc) *Prefix
Delete 添加 DELETE 请求处理项
func (*Prefix) Handle ¶
func (p *Prefix) Handle(path string, h HandlerFunc, method ...string) error
Handle 添加路由项
type Queries ¶
type Queries struct {
// contains filtered or unexported fields
}
Queries 用于处理路径中的查询参数
q,_ := ctx.Queries() page := q.Int64("page", 1) size := q.Int64("size", 20) if q.HasErrors() { // do something return }
func (*Queries) Object ¶
func (q *Queries) Object(v interface{})
Object 将查询参数解析到一个对象中
具体的文档信息可以参考 https://github.com/issue9/query
type Responser ¶ added in v0.40.0
type Responser interface { // Status 状态码 Status() int // Headers 输出的报头 Headers() map[string]string // Body 输出到 body 部分的对象 // // 该对象最终经由 content.Marshal 转换成文本输出。 Body() interface{} }
Responser 表示向客户端输出的对象
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router 路由管理
func (*Router) Delete ¶
func (router *Router) Delete(path string, h HandlerFunc) *Router
Delete 添加 DELETE 请求处理项
func (*Router) Handle ¶
func (router *Router) Handle(path string, h HandlerFunc, method ...string) error
func (*Router) Patch ¶
func (router *Router) Patch(path string, h HandlerFunc) *Router
Patch 添加 PATCH 请求处理项
func (*Router) Path ¶
Path 返回相对于域名的绝对路由地址
功能与 mux.Router.URL 相似,但是加上了关联的域名地址的根路径。比如根地址是 https://example.com/blog pattern 为 /posts/{id},则返回为 /blog/posts/1。 如果 params 为空的话,则会直接将 pattern 作为从 mux 转换之后的内容与 router.root 合并返回。
func (*Router) Post ¶
func (router *Router) Post(path string, h HandlerFunc) *Router
Post 添加 POST 请求处理项
func (*Router) SetDebugger ¶ added in v0.40.0
SetDebugger 设置调试地址
func (*Router) Static ¶
Static 添加静态路由
p 为路由地址,必须以命名参数结尾,比如 /assets/{path},之后可以通过此值删除路由项; dir 为指向静态文件的路径; index 可以在访问一个目录时指定默认访问的页面。
如果要删除该静态路由,则可以将 path 传递给 Remove 进行删除。
比如在 Root 的值为 example.com/blog 时, 将参数指定为 /admin/{path} 和 ~/data/assets/admin 表示将 example.com/blog/admin/* 解析到 ~/data/assets/admin 目录之下。
func (*Router) URL ¶
URL 构建完整的 URL
功能与 mux.Router.URL 相似,但是加上了关联的域名地址。比如根地址是 https://example.com/blog pattern 为 /posts/{id},则返回为 https://example.com/blog/posts/1。 如果 params 为空的话,则会直接将 pattern 作为从 mux 转换之后的内容与 router.root 合并返回。
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server 提供了用于构建 Context 对象的基本数据
func New ¶
New 返回 *Server 实例
name, version 表示服务的名称和版本号; o 指定了初始化 Server 一些非必要参数。在传递给 New 之后,再对其值进行改变,是无效的。
func (*Server) AddResult ¶ added in v0.41.0
func (srv *Server) AddResult(status, code int, phrase localeutil.Phrase)
AddResult 添加错误代码与关联的描述信息
func (*Server) AddResults ¶ added in v0.42.0
func (srv *Server) AddResults(messages map[int]localeutil.Phrase)
AddResult 添加多条错误代码与关联的描述信息
func (*Server) AttachEvent ¶ added in v0.40.0
func (srv *Server) AttachEvent(name string, s Subscriber) (int, error)
AttachEvent 订阅指定事件
返回的值可用于取消订阅。
func (*Server) DetachEvent ¶ added in v0.40.0
DetachEvent 取消对某事件的订阅
func (*Server) DisableCompression ¶ added in v0.40.0
DisableCompression 是否禁用压缩功能
func (*Server) Files ¶ added in v0.41.0
func (srv *Server) Files() *serialization.Files
Files 返回用于序列化文件内容的操作接口
func (*Server) Locale ¶ added in v0.41.0
func (srv *Server) Locale() *serialization.Locale
Locale 返回用于序列化文件内容的操作接口
func (*Server) LocalePrinter ¶ added in v0.41.0
func (*Server) Mimetypes ¶
func (srv *Server) Mimetypes() *serialization.Mimetypes
Mimetypes 返回用于序列化 web 内容的操作接口
func (*Server) NewContext ¶
NewContext 构建 *Context 实例
如果不合规则,会以指定的状码退出。 比如 Accept 的内容与当前配置无法匹配,则退出(panic)并输出 NotAcceptable 状态码。
func (*Server) NewModule ¶ added in v0.40.0
func (srv *Server) NewModule(id, version string, desc localeutil.Phrase, deps ...string) (*Module, error)
NewModule 声明一个新的模块
id 模块名称,需要全局唯一; version 模块的版本信息; desc 模块的详细信息; deps 表示当前模块的依赖模块名称,可以是插件中的模块名称。
func (*Server) NewRouter ¶ added in v0.40.0
func (srv *Server) NewRouter(name string, root string, matcher group.Matcher, filter ...Filter) (*Router, error)
NewRouter 构建基于 matcher 匹配的路由操作实例
func (*Server) RemoveRouter ¶ added in v0.40.0
func (*Server) SetErrorHandle ¶
func (srv *Server) SetErrorHandle(h errorhandler.HandleFunc, status ...int)
SetErrorHandle 设置指定状态码页面的处理函数
如果状态码已经存在处理函数,则修改,否则就添加。
type Subscriber ¶ added in v0.40.0
type Subscriber = events.Subscriber
Subscriber 订阅者函数
data 为事件传递过来的数据,可能存在多个订阅者, 用户不应该直接修改 data 数据,否则结果是未知的。
type Tag ¶
type Tag struct {
// contains filtered or unexported fields
}
Tag 模块下对执行函数的分类
func (*Tag) AddAt ¶ added in v0.40.0
AddAt 添加新的定时任务
f 表示服务的运行函数; title 是对该服务的简要说明; t 指定的时间点; delay 是否在任务执行完之后,才计算下一次的执行时间点。
func (*Tag) AddCron ¶ added in v0.40.0
AddCron 添加新的定时任务
f 表示服务的运行函数; title 是对该服务的简要说明; spec cron 表达式,支持秒; delay 是否在任务执行完之后,才计算下一次的执行时间点。
func (*Tag) AddJob ¶ added in v0.40.0
func (t *Tag) AddJob(title string, f scheduled.JobFunc, scheduler schedulers.Scheduler, delay bool) *Tag
AddJob 添加新的计划任务
f 表示服务的运行函数; title 是对该服务的简要说明; scheduler 计划任务的时间调度算法实现; delay 是否在任务执行完之后,才计算下一次的执行时间点。
func (*Tag) AddRoutes ¶ added in v0.40.0
AddRoutes 注册路由项
f 实际执行注册路由的函数; routerName 路由名称,由 Server.NewRouter 中创建,若为空值,则采用 Tag.Name 作为默认值;