server

package
v0.52.1 Latest Latest
Warning

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

Go to latest
Published: May 22, 2022 License: MIT Imports: 39 Imported by: 2

Documentation

Overview

Package server web 服务管理

Index

Constants

View Source
const (
	DefaultMimetype = "application/octet-stream"
	DefaultCharset  = "utf-8"
)
View Source
const (
	ServiceStopped = scheduled.Stopped // 当前处于停止状态,默认状态
	ServiceRunning = scheduled.Running // 正在运行
	ServiceFailed  = scheduled.Failed  // 出错,不再执行后续操作
)

几种可能的状态值

Variables

This section is empty.

Functions

func IsValidID added in v0.52.0

func IsValidID(id string) bool

IsValidID 是否为合法的 ID

ID 只能是字母、数字、_ 以及 -

Types

type BuildResultFunc added in v0.44.0

type BuildResultFunc func(status int, code, message string) Result

BuildResultFunc 用于生成 Result 接口对象的函数

用户可以通过 BuildResultFunc 返回自定义的 Result 对象, 在 Result 中用户可以自定义其展示方式,可参考默认的实现 DefaultResultBuilder

type CTXSanitizer

type CTXSanitizer interface {
	// CTXSanitize 验证和修正当前对象的数据
	//
	// 如果验证有误,则需要返回这些错误信息。
	CTXSanitize(*Context) ResultFields
}

CTXSanitizer 提供对数据的验证和修正

在 Context.Read 和 Queries.Object 中会在解析数据成功之后,调用该接口进行数据验证。

type Cache added in v0.51.1

type Cache cache.Cache

type CleanupFunc added in v0.51.1

type CleanupFunc func() error

type Context

type Context struct {

	// 保存 Context 在存续期间的可复用变量
	//
	// 这是比 context.Value 更经济的传递变量方式,但是这并不是协程安全的。
	Vars map[any]any
	// contains filtered or unexported fields
}

Context 根据当次 HTTP 请求生成的上下文内容

Context 同时也实现了 http.ResponseWriter 接口, 但是不推荐非必要情况下直接使用 http.ResponseWriter 的接口方法, 而是采用返回 Responser 的方式向客户端输出内容。

func (*Context) Body

func (ctx *Context) Body() (body []byte, err error)

Body 获取用户提交的内容

相对于 ctx.Request().Body,此函数可多次读取。不存在 body 时,返回 nil

func (*Context) ClientIP

func (ctx *Context) ClientIP() string

ClientIP 返回客户端的 IP 地址及端口

获取顺序如下:

  • X-Forwarded-For 的第一个元素
  • Remote-Addr 报头
  • X-Read-IP 报头

func (*Context) Created

func (ctx *Context) Created(v any, location string) Responser

func (*Context) Error

func (ctx *Context) Error(status int, err error) Responser

Error 输出日志到 ERROR 通道并向用户输出指定状态码的页面

func (*Context) Header added in v0.48.0

func (ctx *Context) Header() http.Header

func (*Context) InternalServerError added in v0.49.0

func (ctx *Context) InternalServerError(err error) Responser

InternalServerError 输出日志到 ERROR 通道并向用户输出 500 状态码的页面

func (*Context) IsXHR added in v0.44.0

func (ctx *Context) IsXHR() bool

func (*Context) LanguageTag added in v0.49.0

func (ctx *Context) LanguageTag() language.Tag

func (*Context) LocalePrinter

func (ctx *Context) LocalePrinter() *message.Printer

func (*Context) Location

func (ctx *Context) Location() *time.Location

func (*Context) Logs added in v0.44.0

func (ctx *Context) Logs() *logs.Logs

func (*Context) Marshal

func (ctx *Context) Marshal(status int, body any) error

Marshal 向客户端输出内容

status 想输出给用户状态码,如果出错,那么最终展示给用户的状态码可能不是此值; body 表示输出的对象,该对象最终调用 ctx.outputMimetype 编码;

func (*Context) NewValidation added in v0.52.0

func (ctx *Context) NewValidation(separator string) *validation.Validation

NewValidation 声明验证器

separator 用于指定字段名称上下级元素名称之间的连接符。比如在返回 xml 元素时, 可能会采用 root/element 的格式表示上下级,此时 separator 应设置为 /。 而在 json 中,可能会被转换成 root.element 的格式。

可以配置 CTXSanitizer 接口使用:

type User struct {
    Name string
    Age int
}
func(o *User) CTXSanitize(ctx* web.Context) web.ResultFields {
    v := ctx.NewValidation(".")
    return v.NewField(o.Name, "name", validator.Required().Message("不能为空")).
        NewField(o.Age, "age", validator.Min(18).Message("不能小于 18 岁")).
        Messages()
}

如果需要更加精细的控制,可以调用 github.com/issue9/validation.New 进行声明。

func (*Context) NoContent

func (ctx *Context) NoContent() Responser

func (*Context) NotFound

func (ctx *Context) NotFound() Responser

func (*Context) NotImplemented

func (ctx *Context) NotImplemented() Responser

func (*Context) Now

func (ctx *Context) Now() time.Time

Now 返回以 ctx.Location 为时区的当前时间

func (*Context) OK added in v0.50.0

func (ctx *Context) OK(v any) Responser

OK 返回 200 状态码下的对象

func (*Context) Object added in v0.50.0

func (ctx *Context) Object(status int, body interface{}, kv ...string) Responser

Object 输出状态和对象至客户端

body 表示需要输出的对象,该对象最终会被转换成相应的编码; kv 为报头,必须以偶数数量出现,奇数位为报头名,偶数位为对应的报头值;

func (*Context) OnExit added in v0.49.0

func (ctx *Context) OnExit(f func(int))

OnExit 注册退出当前请求时的处理函数

f 的原型为

func(status int)

其中 status 为最终输出到客户端的状态码。

func (*Context) ParamID

func (ctx *Context) ParamID(key, code string) (int64, Responser)

ParamID 获取地址参数中表示 key 的值并并转换成大于 0 的 int64

相对于 Context.ParamInt64(),该值必须大于 0。

NOTE: 若需要获取多个参数,使用 Context.Params 会更方便。

func (*Context) ParamInt64

func (ctx *Context) ParamInt64(key, code string) (int64, Responser)

ParamInt64 取地址参数中的 key 表示的值 int64 类型值

NOTE: 若需要获取多个参数,可以使用 Context.Params 获取会更方便。

func (*Context) ParamString

func (ctx *Context) ParamString(key, code string) (string, Responser)

ParamString 取地址参数中的 key 表示的 string 类型值

NOTE: 若需要获取多个参数,可以使用 Context.Params 获取会更方便。

func (*Context) Params

func (ctx *Context) Params() *Params

Params 声明一个新的 Params 实例

func (*Context) ParseTime

func (ctx *Context) ParseTime(layout, value string) (time.Time, error)

ParseTime 分析基于当前时区的时间

func (*Context) Queries

func (ctx *Context) Queries() (*Queries, error)

Queries 声明一个新的 Queries 实例

func (*Context) QueryObject

func (ctx *Context) QueryObject(v any, code string) Responser

QueryObject 将查询参数解析到一个对象中

func (*Context) Read

func (ctx *Context) Read(v any, code string) Responser

Read 从客户端读取数据并转换成 v 对象

功能与 Unmarshal() 相同,只不过 Read() 在出错时,返回的不是 error, 而是一个表示错误信息的 Response 对象。

如果 v 实现了 CTXSanitizer 接口,则在读取数据之后,会调用其接口函数。 如果验证失败,会输出以 code 作为错误代码的 Response 对象。

func (*Context) Redirect added in v0.44.0

func (ctx *Context) Redirect(status int, url string) Responser

Redirect 重定向至新的 URL

func (*Context) Request

func (ctx *Context) Request() *http.Request

Request 返回原始的请求对象

NOTE: 如果需要使用 context.Value 在 Request 中附加值,请使用 ctx.Vars

func (*Context) Result added in v0.40.0

func (ctx *Context) Result(code string, fields ResultFields) Responser

Result 向客户端输出指定代码的错误信息

如果找不到 code 对应的错误信息,则会直接 panic。

func (*Context) RetryAfter added in v0.50.0

func (ctx *Context) RetryAfter(status int, seconds uint64) Responser

RetryAfter 返回 Retry-After 报头内容

一般适用于 301 和 503 报文。

status 表示返回的状态码;seconds 表示秒数,如果想定义为时间格式, 可以采用 RetryAt 函数,两个功能是相同的,仅是时间格式上有差别。

func (*Context) RetryAt added in v0.50.0

func (ctx *Context) RetryAt(status int, at time.Time) Responser

func (*Context) Server

func (ctx *Context) Server() *Server

Server 获取关联的 Server 实例

func (*Context) SetLanguage added in v0.49.0

func (ctx *Context) SetLanguage(l string) error

SetLanguage 设置输出的语言

默认情况下,会根据用户提交的 Accept-Language 报头设置默认值。

func (*Context) SetLocation added in v0.49.0

func (ctx *Context) SetLocation(name string) error

SetLocation 设置时区信息

name 为时区名称,比如 'America/New_York',具体说明可参考 time.LoadLocataion

func (*Context) Sprintf

func (ctx *Context) Sprintf(key message.Reference, v ...any) string

Sprintf 返回翻译后的结果

func (*Context) Status added in v0.50.0

func (ctx *Context) Status(code int, kv ...string) Responser

Status 仅向客户端输出状态码和报头

kv 为报头,必须以偶数数量出现,奇数位为报头名,偶数位为对应的报头值;

func (*Context) Unmarshal

func (ctx *Context) Unmarshal(v any) error

Unmarshal 将提交的内容转换成 v 对象

func (*Context) Write added in v0.48.0

func (ctx *Context) Write(bs []byte) (int, error)

func (*Context) WriteHeader added in v0.48.0

func (ctx *Context) WriteHeader(status int)

type HandlerFunc

type HandlerFunc func(*Context) Responser

HandlerFunc 路由项处理函数原型

最终调用 Responser.Apply 向客户端输出信息。

type Middleware added in v0.48.0

type Middleware = mux.MiddlewareOf[HandlerFunc]

type MiddlewareFunc added in v0.48.0

type MiddlewareFunc = mux.MiddlewareFuncOf[HandlerFunc]

type Module

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

func (*Module) AddFS added in v0.41.0

func (m *Module) AddFS(fsys ...fs.FS)

AddFS 添加文件系统

Module 默认以 id 为名称相对于 Server 创建了一个文件系统, 此操作会将 fsys 作为 Module 另一个文件系统与 Module 相关联, 当执行 Open 等操作时,会依然以关联顺序查找相应的文件系统,直到找到。

需要注意的是,fs.Glob 不是搜索所有的 fsys 然后返回集合。

func (*Module) AddResult added in v0.48.0

func (m *Module) AddResult(status int, code string, phrase localeutil.LocaleStringer)

AddResult 注册错误代码

此功能与 Server.AddResult 的唯一区别是,code 参数会加上 Module.ID() 作为其前缀。

func (*Module) AddResults added in v0.48.0

func (m *Module) AddResults(status int, messages map[string]localeutil.LocaleStringer)

AddResults 添加多条错误信息

此功能与 Server.AddResult 的唯一区别是,code 参数会加上 Module.ID() 作为其前缀。

func (*Module) BuildID added in v0.51.1

func (m *Module) BuildID(suffix ...string) string

BuildID 以 Module.ID() + "_" 为前缀生成一个新的字符串

func (*Module) Cache added in v0.48.0

func (m *Module) Cache() cache.Access

Cache 获取缓存对象

该缓存对象的 key 会自动添加 Module.ID 作为其前缀。

func (*Module) FileServer added in v0.48.0

func (m *Module) FileServer(name, index string) HandlerFunc

FileServer 返回以当前模块作为文件系统的静态文件服务

func (*Module) Glob added in v0.48.0

func (m *Module) Glob(pattern string) ([]string, error)

func (*Module) ID

func (m *Module) ID() string

ID 模块的唯一 ID

func (*Module) LoadLocale added in v0.41.0

func (m *Module) LoadLocale(glob string) error

LoadLocale 加载当前模块文件系统下的本地化文件

func (*Module) Open added in v0.41.0

func (m *Module) Open(name string) (fs.File, error)

func (*Module) Server added in v0.40.0

func (m *Module) Server() *Server

type Options

type Options struct {
	// 项目默认可存取的文件系统
	//
	// 默认情况下为可执行文件所在的目录。
	FS fs.FS

	// 服务器的时区
	//
	// 默认值为 time.Local
	Location *time.Location

	// 指定生成 Result 数据的方法
	//
	// 默认情况下指向  DefaultResultBuilder。
	ResultBuilder BuildResultFunc

	// 缓存系统
	//
	// 默认值为内存类型。
	Cache Cache

	// 端口号
	//
	// 格式参照 net/http.Server.Addr 字段。
	// 可以为空,表示由 net/http.Server 确定其默认值。
	//
	// NOTE: 该值可能会被 HTTPServer 的操作所覆盖。
	Port string

	// 可以对 http.Server 的内容进行修改
	//
	// NOTE: 对 http.Server.Handler 的修改不会启作用,该值始终会指向 Server.routers
	HTTPServer func(*http.Server)

	// 日志的输出通道设置
	//
	// 如果此值为空,那么在被初始化 logs.New(nil) 值,表示不会输出到任何通道。
	Logs *logs.Logs

	// 指定用于序列化文件的方法
	//
	// 该对象同时被用于加载配置文件和序列化文件。如果为空,会初始化一个空对象。
	FileSerializers *serialization.Files

	// 压缩对象
	//
	// 可以为空,表示不支持压缩功能。
	Encodings *serialization.Encodings

	// 对数据编解码的支持
	//
	// 如果此内容为空,那么所有请求都将返回 404,且无法解析任意的提交的内容。
	Mimetypes *serialization.Mimetypes

	// 默认的语言标签
	//
	// 在用户请求的报头中没有匹配的语言标签时,会采用此值作为该用户的本地化语言,
	// 同时也用来初始化 Server.LocalePrinter。
	//
	// 如果为空,则会尝试读取当前系统的本地化信息。
	LanguageTag language.Tag

	// 本地化操作的对象
	//
	// 与 FileSerializers 组合构建 serialization.Locale 对象,可以为空。
	Catalog *catalog.Builder

	// 退出项目时执行的操作
	//
	// 数组的元素越靠后越早执行,且在此处指定的项目会晚于 Server.OnClose 执行。
	Cleanup []CleanupFunc
	// 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

func (p *Params) Bool(key string) bool

Bool 获取参数 key 所代表的值并转换成 bool

最终会调用 strconv.ParseBool 进行转换, 也只有该方法中允许的字符串会被正确转换。

func (*Params) Errors

func (p *Params) Errors() ResultFields

Errors 返回所有的错误信息

func (*Params) Float64

func (p *Params) Float64(key string) float64

Float64 获取参数 key 所代表的值并转换成 float64

func (*Params) HasErrors

func (p *Params) HasErrors() bool

HasErrors 是否有错误内容存在

func (*Params) ID

func (p *Params) ID(key string) int64

ID 获取参数 key 所代表的值并转换成 int64

值必须大于 0,否则会输出错误信息,并返回零值。

func (*Params) Int64

func (p *Params) Int64(key string) int64

Int64 获取参数 key 所代表的值,并转换成 int64

func (*Params) MustBool

func (p *Params) MustBool(key string, def bool) bool

MustBool 获取参数 key 所代表的值并转换成 bool

若不存在或是转换出错,则返回 def 作为其默认值。 仅在类型转换出错时,才会向 errors 写入错误信息。

最终会调用 strconv.ParseBool 进行转换, 也只有该方法中允许的字符串会被正确转换。

func (*Params) MustFloat64

func (p *Params) MustFloat64(key string, def float64) float64

MustFloat64 获取参数 key 所代表的值并转换成 float64

若不存在或是转换出错,则返回 def 作为其默认值。 仅在类型转换出错时,才会向 errors 写入错误信息。

func (*Params) MustID

func (p *Params) MustID(key string, def int64) int64

MustID 获取参数 key 所代表的值并转换成 int64

值必须大于 0,否则会输出错误信息,并返回零值。

若不存在或是转换出错,则返回 def 作为其默认值。 仅在类型转换出错或是小于零时,才会向 errors 写入错误信息。

func (*Params) MustInt64

func (p *Params) MustInt64(key string, def int64) int64

MustInt64 获取参数 key 所代表的值并转换成 int64

若不存在或是转换出错,则返回 def 作为其默认值。 仅在类型转换出错时,才会向 errors 写入错误信息。

func (*Params) MustString

func (p *Params) MustString(key, def string) string

MustString 获取参数 key 所代表的值并转换成 string

若不存在或是转换出错,则返回 def 作为其默认值。

func (*Params) Result

func (p *Params) Result(code string) Responser

Result 转换成 Result 对象

func (*Params) String

func (p *Params) String(key string) string

String 获取参数 key 所代表的值并转换成 string

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) Bool

func (q *Queries) Bool(key string, def bool) bool

Bool 从查询参数中获取指定名称的值

若不存在则返回 def 作为其默认值。

func (*Queries) Errors

func (q *Queries) Errors() ResultFields

Errors 所有的错误信息

func (*Queries) Float64

func (q *Queries) Float64(key string, def float64) float64

Float64 从查询参数中获取指定名称的值

若不存在则返回 def 作为其默认值。

func (*Queries) HasErrors

func (q *Queries) HasErrors() bool

HasErrors 是否存在错误内容

func (*Queries) Int

func (q *Queries) Int(key string, def int) int

Int 从查询参数中获取指定名称的值

若不存在则返回 def 作为其默认值。 若是无法转换,则会保存错误信息

func (*Queries) Int64

func (q *Queries) Int64(key string, def int64) int64

Int64 从查询参数中获取指定名称的值

若不存在则返回 def 作为其默认值。

func (*Queries) Object

func (q *Queries) Object(v any)

Object 将查询参数解析到一个对象中

具体的文档信息可以参考 https://github.com/issue9/query

如果 v 实现了 CTXSanitizer 接口,则在读取数据之后,会调用其接口函数。 如果验证失败,错误信息存入 q.errors。

NOTE: query.Sanitizer 接口和 CTXSanitizer 接口同时拥有验证数据的功能, v 只要实现其中的一个接口即可,否则会多次调用验证。

func (*Queries) Result

func (q *Queries) Result(code string) Responser

Result 转换成 Response 对象

func (*Queries) String

func (q *Queries) String(key, def string) string

String 从查询参数中获取指定名称的值

若不存在则返回 def 作为其默认值。

type Responser added in v0.40.0

type Responser interface {
	// Apply 通过 *Context 将当前内容渲染到客户端
	//
	// 在调用 Apply 之后,就不再使用 Responser 对象,
	// 如果你的对象支持 sync.Pool 复用,可以在 Apply 退出之际进行回收至 sync.Pool。
	Apply(*Context)
}

Responser 表示向客户端输出对象最终需要实现的接口

func Status added in v0.40.0

func Status(code int) Responser

Status 仅向客户端输出状态码

type Result

type Result interface {
	Responser

	// Add 添加详细的错误信息
	//
	// 相同的 key 应该能关联多个 val 值。
	Add(key string, val ...string)

	// Set 设置详细的错误信息
	//
	// 如果已经相同的 key,会被覆盖。
	Set(key string, val ...string)

	// HasFields 是否存在详细的错误信息
	//
	// 如果有通过 Add 添加内容,那么应该返回 true
	HasFields() bool
}

Result 展示错误代码需要实现的接口

func DefaultResultBuilder added in v0.44.0

func DefaultResultBuilder(status int, code, message string) Result

DefaultResultBuilder 默认的 BuildResultFunc 实现

支持以下格式的返回信息:

JSON:

{
    'message': 'error message',
    'code': '4000001',
    'fields':[
        {'name': 'username': 'message': ['名称过短', '不能包含特殊符号']},
        {'name': 'password': 'message': ['不能为空']},
    ]
}

XML:

<result code="400">
    <message>error message</message>
    <field name="username">
        <message>名称过短</message>
        <message>不能包含特殊符号</message>
    </field>
    <field name="password"><message>不能为空</message></field>
</result>

YAML:

message: 'error message'
code: '40000001'
fields:
  - name: username
    message:
      - 名称过短
      - 不能包含特殊符号
  - name: password
    message:
      - 不能为空

protobuf:

message Result {
    string message = 1;
    string code = 2;
    repeated Field fields = 3;
}

message Field {
    string name = 1;
    repeated string message = 2;
}

FormData:

message=errormessage&code=4000001&fields.username=名称过短&fields.username=不能包含特殊符号&fields.password=不能为空

protobuf

message Result {
    string message = 1;
    string code = 2;
    repeated Field fields = 3;
}

message Field {
    string name = 1;
    repeated string message = 2;
}

type ResultFields added in v0.44.0

type ResultFields = validation.Messages

ResultFields 表示字段的错误信息列表

原始类型为 map[string][]string,键名为字段名,键值为错误信息列表。

type Router

type Router = mux.RouterOf[HandlerFunc]

type RouterOptions added in v0.48.0

type RouterOptions = mux.Options

type Routers added in v0.48.0

type Routers = mux.RoutersOf[HandlerFunc]

type ScheduledJob added in v0.44.0

type ScheduledJob = scheduled.Job

type ScheduledJobFunc added in v0.44.0

type ScheduledJobFunc = scheduled.JobFunc

type Scheduler added in v0.44.0

type Scheduler = scheduled.Scheduler

type Server

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

Server 提供 HTTP 服务

func New

func New(name, version string, o *Options) (*Server, error)

New 返回 *Server 实例

name, version 表示服务的名称和版本号; o 指定了初始化 Server 一些非必要参数。在传递给 New 之后,再对其值进行改变,是无效的。

func (*Server) AddAt added in v0.44.0

func (srv *Server) AddAt(title string, f ScheduledJobFunc, ti time.Time, delay bool)

AddAt 添加新的定时任务

f 表示服务的运行函数; title 是对该服务的简要说明; t 指定的时间点; delay 是否在任务执行完之后,才计算下一次的执行时间点。

func (*Server) AddCron added in v0.44.0

func (srv *Server) AddCron(title string, f ScheduledJobFunc, spec string, delay bool)

AddCron 添加新的定时任务

f 表示服务的运行函数; title 是对该服务的简要说明; spec cron 表达式,支持秒; delay 是否在任务执行完之后,才计算下一次的执行时间点。

func (*Server) AddJob added in v0.44.0

func (srv *Server) AddJob(title string, f ScheduledJobFunc, scheduler Scheduler, delay bool)

AddJob 添加新的计划任务

f 表示服务的运行函数; title 是对该服务的简要说明; scheduler 计划任务的时间调度算法实现; delay 是否在任务执行完之后,才计算下一次的执行时间点。

func (*Server) AddResult added in v0.41.0

func (srv *Server) AddResult(status int, code string, phrase localeutil.LocaleStringer)

AddResult 添加一条错误信息

status 指定了该错误代码反馈给客户端的 HTTP 状态码;

func (*Server) AddResults added in v0.42.0

func (srv *Server) AddResults(status int, messages map[string]localeutil.LocaleStringer)

AddResults 添加多条错误信息

func (*Server) AddService added in v0.44.0

func (srv *Server) AddService(title string, f ServiceFunc)

AddService 添加新的服务

f 表示服务的运行函数; title 是对该服务的简要说明。

NOTE: 如果 Manager 的所有服务已经处于运行的状态,则会自动运行新添加的服务。

func (*Server) AddTicker added in v0.44.0

func (srv *Server) AddTicker(title string, f ScheduledJobFunc, dur time.Duration, imm, delay bool)

AddTicker 添加新的定时任务

f 表示服务的运行函数; title 是对该服务的简要说明; dur 时间间隔; imm 是否立即执行一次该任务; delay 是否在任务执行完之后,才计算下一次的执行时间点。

func (*Server) Cache

func (srv *Server) Cache() Cache

Cache 返回缓存的相关接口

func (*Server) Close

func (srv *Server) Close(shutdownTimeout time.Duration) error

Close 触发关闭操作

需要等待 Server.Serve 返回才能证整个服务被关闭。

func (*Server) FileServer added in v0.44.0

func (srv *Server) FileServer(fsys fs.FS, name, index string) HandlerFunc

FileServer 提供静态文件服务

fsys 为文件系统,如果为空则采用 srv.FS; name 表示参数名称; index 表示目录下的默认文件名;

func (*Server) Files added in v0.41.0

func (srv *Server) Files() *serialization.Files

Files 返回用于序列化文件内容的操作接口

func (*Server) Jobs added in v0.44.0

func (srv *Server) Jobs() []*ScheduledJob

Jobs 返回所有的计划任务

func (*Server) Locale added in v0.41.0

func (srv *Server) Locale() *serialization.Locale

Locale 操作操作本地化文件的接口

func (*Server) LocalePrinter added in v0.41.0

func (srv *Server) LocalePrinter() *message.Printer

func (*Server) Location

func (srv *Server) Location() *time.Location

Location 指定服务器的时区信息

func (*Server) Logs

func (srv *Server) Logs() *logs.Logs

Logs 返回关联的 logs.Logs 实例

func (*Server) Name

func (srv *Server) Name() string

Name 应用的名称

func (*Server) NewContext

func (srv *Server) NewContext(w http.ResponseWriter, r *http.Request) *Context

NewContext 构建 *Context 实例

如果不合规则,则会向 w 输出状态码并返回 nil。

func (*Server) NewModule added in v0.40.0

func (srv *Server) NewModule(id string) *Module

NewModule 声明新的模块

id 模块的 ID,需要全局唯一,只能是字母、数字以及下划线。

func (*Server) Now

func (srv *Server) Now() time.Time

Now 返回当前时间

与 time.Now() 的区别在于 Now() 基于当前时区

func (*Server) OnClose added in v0.44.0

func (srv *Server) OnClose(f CleanupFunc)

OnClose 注册关闭服务时需要执行的函数

NOTE: 按注册的相反顺序执行。

func (*Server) Open

func (srv *Server) Open(name string) (fs.File, error)

Open 实现 fs.FS 接口

func (*Server) ParseTime

func (srv *Server) ParseTime(layout, value string) (time.Time, error)

ParseTime 分析基于当前时区的时间

func (*Server) Result added in v0.41.0

func (srv *Server) Result(p *message.Printer, code string, fields ResultFields) Result

Result 返回 Result 实例

如果找不到 code 对应的错误信息,则会直接 panic。 fields 表示明细字段,可以为空,之后通过 Result.Add 添加。

func (*Server) Results added in v0.41.0

func (srv *Server) Results(p *message.Printer) map[string]string

Results 返回错误代码以及对应的说明内容

func (*Server) Routers added in v0.44.0

func (srv *Server) Routers() *Routers

Routers 路由管理接口

func (*Server) Serve

func (srv *Server) Serve() (err error)

Serve 启动服务

会等待 Server.Close() 执行完之后,此函数才会返回,这一点与 Http.ListenAndServe 稍有不同。 一旦返回,整个 Server 对象将处于不可用状态。

func (*Server) Services

func (srv *Server) Services() []*Service

Services 返回长期运行的服务函数列表

func (*Server) Serving added in v0.44.0

func (srv *Server) Serving() bool

Serving 是否处于服务状态

func (*Server) Tag added in v0.41.0

func (srv *Server) Tag() language.Tag

Tag 返回默认的语言标签

func (*Server) Uptime

func (srv *Server) Uptime() time.Time

Uptime 当前服务的运行时间

func (*Server) Vars added in v0.42.0

func (srv *Server) Vars() *sync.Map

Vars 操纵共享变量的接口

func (*Server) Version

func (srv *Server) Version() string

Version 应用的版本

type Service added in v0.44.0

type Service struct {
	Title string
	// contains filtered or unexported fields
}

Service 服务模型

func (*Service) Err added in v0.44.0

func (srv *Service) Err() error

Err 上次的错误信息,不会清空。

func (*Service) Run added in v0.44.0

func (srv *Service) Run()

Run 开始执行该服务

func (*Service) State added in v0.44.0

func (srv *Service) State() ServiceState

State 获取当前服务的状态

func (*Service) Stop added in v0.44.0

func (srv *Service) Stop()

Stop 停止服务

type ServiceFunc added in v0.45.0

type ServiceFunc func(ctx context.Context) error

ServiceFunc 服务实际需要执行的函数

实现者需要正确处理 ctx.Done 事件,调用者可能会主动取消函数执行; 如果是通 ctx.Done 取消的,应该返回 context.Canceled。

type ServiceState added in v0.44.0

type ServiceState = scheduled.State

ServiceState 服务的状态值

Directories

Path Synopsis
Package servertest 针对 server 的测试用例
Package servertest 针对 server 的测试用例

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
JackTT - Gopher 🇻🇳