web

package module
v0.86.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2023 License: MIT Imports: 35 Imported by: 75

README

web

Test Cache Go Report Card codecov PkgGoDev Go version License

web 是一个比较完整的 API 开发框架,相对于简单的路由,提供了更多的便利功能。 如果你只是需要一个简单的路由工具,那么你可以移步到 mux

package main

import "github.com/issue9/web"
import "github.com/issue9/web/server"

// main.go
func main() {
    srv := server.New("web", "1.0.0", &web.Options{})
    router := srv.Routers().NewRouter()
    router.Get("/admins", getAdmins).
        Get("/groups", getGroups)

    srv.Serve()
}

func getAdmins(ctx* web.Context) web.Responser {
    return ctx.NotImplemented();
}

func getGroups(ctx* web.Context) web.Responser {
    return ctx.NotImplemented();
}

字符集和文档类型

https://www.iana.org/assignments/character-sets/character-sets.xhtml 中列出的字符集都能自动转换。 文档类型由 Server.Mimetypes 指定。

import "github.com/issue9/web"
import "github.com/issue9/web/server"

srv := server.New("app", "1.0.0", &server.Options{
    Mimetypes: []*server.Mimetype{
        { Type: "application/json", ProblemType: "application/problem+json", Marshal: json.Marshal, Unmarshal: json.Unmarshal },
        { Type: "application/xml", ProblemType: "application/problem+xml", Marshal: xml.Marshal, Unmarshal: xml.Unmarshal },
    }
})

srv.Serve()

客户端只要在请求时设置 Accept 报头就可返回相应类型的数据,而 Accept-Charset 报头可设置接收的字符集。 Content-Type 则可以有向服务器指定提交内容的文档类型和字符集。

错误处理

框架根据 RFC7807 提供了一种输出错误信息内容的机制。

中间件

工具

https://github.com/issue9/web/releases 提供了一个简易的辅助工具。可以帮助用户完成以下工作:

  • 提取和更新本地化信息;
  • 生成 openapi 文档。需要在注释中写一定的注解;
  • 热编译项目;

macOS 和 linux 用户可以直接使用 brew 进行安装:

brew tap caixw/brew
brew install caixw/brew/web

版权

本项目采用 MIT 开源授权许可证,完整的授权说明可在 LICENSE 文件中找到。

Documentation

Overview

Package web 通用的 web 开发框架

Index

Constants

View Source
const (
	ProblemAboutBlank = "about:blank"

	ProblemBadRequest                    = "400"
	ProblemUnauthorized                  = "401"
	ProblemPaymentRequired               = "402"
	ProblemForbidden                     = "403"
	ProblemNotFound                      = "404"
	ProblemMethodNotAllowed              = "405"
	ProblemNotAcceptable                 = "406"
	ProblemProxyAuthRequired             = "407"
	ProblemRequestTimeout                = "408"
	ProblemConflict                      = "409"
	ProblemGone                          = "410"
	ProblemLengthRequired                = "411"
	ProblemPreconditionFailed            = "412"
	ProblemRequestEntityTooLarge         = "413"
	ProblemRequestURITooLong             = "414"
	ProblemUnsupportedMediaType          = "415"
	ProblemRequestedRangeNotSatisfiable  = "416"
	ProblemExpectationFailed             = "417"
	ProblemTeapot                        = "418"
	ProblemMisdirectedRequest            = "421"
	ProblemUnprocessableEntity           = "422"
	ProblemLocked                        = "423"
	ProblemFailedDependency              = "424"
	ProblemTooEarly                      = "425"
	ProblemUpgradeRequired               = "426"
	ProblemPreconditionRequired          = "428"
	ProblemTooManyRequests               = "429"
	ProblemRequestHeaderFieldsTooLarge   = "431"
	ProblemUnavailableForLegalReasons    = "451"
	ProblemInternalServerError           = "500"
	ProblemNotImplemented                = "501"
	ProblemBadGateway                    = "502"
	ProblemServiceUnavailable            = "503"
	ProblemGatewayTimeout                = "504"
	ProblemHTTPVersionNotSupported       = "505"
	ProblemVariantAlsoNegotiates         = "506"
	ProblemInsufficientStorage           = "507"
	ProblemLoopDetected                  = "508"
	ProblemNotExtended                   = "510"
	ProblemNetworkAuthenticationRequired = "511"
)
View Source
const (
	Stopped = scheduled.Stopped // 停止状态,默认状态
	Running = scheduled.Running // 正在运行
	Failed  = scheduled.Failed  // 出错,不再执行后续操作
)

服务的几种状态

View Source
const Version = "0.86.0"

Version 当前框架的版本

Variables

This section is empty.

Functions

func ErrUnsupportedSerialization added in v0.83.1

func ErrUnsupportedSerialization() error

ErrUnsupportedSerialization 返回不支持序列化的错误信息

func NewError added in v0.85.0

func NewError(status int, err error) error

NewError 用 HTTP 状态码包装一个错误信息

status 表示 HTTP 状态码; err 被包装的错误信息,如果所有错误都是空值,将会 panic;

此方法返回的错误,在 Context.Error 会被识别且按指定的状态码输出。

func NewLocaleError added in v0.62.0

func NewLocaleError(format string, v ...any) error

NewLocaleError 本地化的错误信息

func NewStackError added in v0.61.0

func NewStackError(err error) error

NewStackError 为 err 带上调用信息

位置从调用 NewStackError 开始。如果 err 为 nil,则返回 nil。 多次调用 NewStackError 包装,则返回第一次包装的返回值。

func SelectorRewrite added in v0.86.0

func SelectorRewrite(s Selector, l Logger) func(*httputil.ProxyRequest)

SelectorRewrite 将 Selector 转换成适用于 httputil.ReverseProxy.Rewrite 的方法

p := &httputil.ReverseProxy{Rewrite: SelectorRewrite(s)}

Types

type Cache added in v0.51.1

type Cache = cache.Cache

Cache 缓存内容的访问接口

type Client added in v0.85.0

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

Client 用于访问远程的客户端

NOTE: 远程如果不是 Server 实现的服务,可能无法正确处理返回对象。

func NewClient added in v0.85.0

func NewClient(client *http.Client, codec *Codec, selector Selector, marshalName string, marshal func(any) ([]byte, error)) *Client

NewClient 创建 Client 实例

client 要以为空,表示采用 &http.Client{} 作为默认值; marshalName 和 marshal 表示编码的名称和方法;

func (*Client) Client added in v0.85.0

func (c *Client) Client() *http.Client

func (*Client) Delete added in v0.85.0

func (c *Client) Delete(path string, resp any, problem *RFC7807) error

func (*Client) Do added in v0.85.0

func (c *Client) Do(method, path string, req, resp any, problem *RFC7807) error

Do 开始新的请求

req 为提交的对象,最终是由初始化参数的 marshal 进行编码; resp 为返回的数据的写入对象,必须是指针类型; problem 为返回出错时的写入对象,如果包含自定义的 Extensions 字段,需要为其初始化为零值。 RFC7807 同时也实现了 error 接口,如果不需要特殊处理,可以直接作为错误处理; 非 HTTP 状态码错误返回 err;

func (*Client) Get added in v0.85.0

func (c *Client) Get(path string, resp any, problem *RFC7807) error

func (*Client) NewRequest added in v0.85.0

func (c *Client) NewRequest(method, path string, body any) (resp *http.Request, err error)

NewRequest 生成 http.Request

body 为需要提交的对象,采用 [Client.marshal] 进行序列化;

func (*Client) ParseResponse added in v0.85.0

func (c *Client) ParseResponse(rsp *http.Response, resp any, problem *RFC7807) (err error)

ParseResponse 从 http.Response 解析并获取返回对象

如果正常状态,将内容解码至 resp,如果出错了,则解码至 problem。其它情况下返回错误信息。

func (*Client) Patch added in v0.85.0

func (c *Client) Patch(path string, req, resp any, problem *RFC7807) error

func (*Client) Post added in v0.85.0

func (c *Client) Post(path string, req, resp any, problem *RFC7807) error

func (*Client) Put added in v0.85.0

func (c *Client) Put(path string, req, resp any, problem *RFC7807) error

func (*Client) URL added in v0.85.0

func (c *Client) URL(path string) string

URL 生成一条访问地址

type Codec added in v0.86.0

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

Codec 编码解码工具

包含了压缩方法和媒体类型的处理

func NewCodec added in v0.86.0

func NewCodec() *Codec

NewCodec 声明 Codec 对象

func (*Codec) AddCompressor added in v0.86.0

func (e *Codec) AddCompressor(c Compressor, t ...string) *Codec

AddCompressor 添加新的压缩算法

t 表示适用的 content-type 类型,可以包含通配符,比如:

	application/json
	text/*
 *

如果为空,则和 * 是相同的,表示匹配所有。

func (*Codec) AddMimetype added in v0.86.0

func (e *Codec) AddMimetype(name string, m MarshalFunc, u UnmarshalFunc, problem string) *Codec

AddMimetype 添加对媒体类型的编解码函数

type Compressor added in v0.85.0

type Compressor interface {
	// Name 算法的名称
	Name() string

	// NewDecoder 将 r 包装成为当前压缩算法的解码器
	NewDecoder(r io.Reader) (io.ReadCloser, error)

	// NewEncoder 将 w 包装成当前压缩算法的编码器
	NewEncoder(w io.Writer) (io.WriteCloser, error)
}

Compressor 压缩算法的接口

type Context

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

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

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

func (*Context) Begin added in v0.83.0

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

Begin 当前对象的初始化时间

func (*Context) Charset added in v0.83.0

func (ctx *Context) Charset() string

Charset 输出的字符集

func (*Context) ClientIP added in v0.34.0

func (ctx *Context) ClientIP() string

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

获取顺序如下:

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

func (*Context) Encoding added in v0.83.0

func (ctx *Context) Encoding() string

Encoding 输出的压缩编码名称

func (*Context) Error added in v0.34.0

func (ctx *Context) Error(err error, id string) Problem

Error 将 err 输出到 ERROR 通道并尝试以指定 id 的 Problem 返回

如果 id 为空,尝试以下顺序获得值:

func (*Context) Free added in v0.86.0

func (ctx *Context) Free()

func (*Context) GetVar added in v0.83.0

func (ctx *Context) GetVar(key any) (any, bool)

GetVar 返回指定名称的变量

func (*Context) Header added in v0.83.0

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

func (*Context) ID added in v0.83.0

func (ctx *Context) ID() string

ID 当前请求的唯一 ID

一般源自客户端的 X-Request-ID 报头,如果不存在,则由 [Server.UniqueID] 生成。

func (*Context) IsXHR added in v0.83.0

func (ctx *Context) IsXHR() bool

func (*Context) LanguageTag added in v0.83.0

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

func (*Context) LocalePrinter added in v0.34.0

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

func (*Context) Logs added in v0.83.0

func (ctx *Context) Logs() Logs

Logs 返回日志操作对象

该返回实例与 [Server.Logs] 是不同的, 当前返回实例的日志输出时会带上当前请求的 Context.ID 作为额外参数。

func (*Context) Marshal added in v0.34.0

func (ctx *Context) Marshal(v any) ([]byte, error)

Marshal 将对象 v 按用户要求编码并返回

func (*Context) Mimetype added in v0.83.0

func (ctx *Context) Mimetype(problem bool) string

Mimetype 返回输出编码名称

problem 表示是否返回 problem 状态时的值。

func (*Context) NotFound added in v0.34.0

func (ctx *Context) NotFound() Problem

func (*Context) NotImplemented added in v0.34.0

func (ctx *Context) NotImplemented() Problem

func (*Context) OnExit added in v0.83.0

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

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

f 为执行的方法,其原型为:

func(ctx *Context, status int)

其中 ctx 即为当前实例,status 则表示实际输出的状态码。

NOTE: 以注册的相反顺序调用这些方法。

func (*Context) PathID added in v0.83.0

func (ctx *Context) PathID(key, id string) (int64, Problem)

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

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

func (*Context) PathInt64 added in v0.83.0

func (ctx *Context) PathInt64(key, id string) (int64, Problem)

PathInt64 取地址参数中的 key 表示的值并尝试转换成 int64 类型

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

func (*Context) PathString added in v0.83.0

func (ctx *Context) PathString(key, id string) (string, Problem)

PathString 取地址参数中的 key 表示的值并转换成 string 类型

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

func (*Context) Paths added in v0.83.0

func (ctx *Context) Paths(exitAtError bool) *Paths

Paths 声明一个用于获取路径参数的对象

返回对象的生命周期在 Context 结束时也随之结束。

func (*Context) Problem added in v0.83.0

func (ctx *Context) Problem(id string) Problem

Problem 返回指定 id 的 Problem

func (*Context) Queries added in v0.34.0

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

Queries 声明一个用于获取查询参数的对象

返回对象的生命周期在 Context 结束时也随之结束。

func (*Context) QueryObject added in v0.34.0

func (ctx *Context) QueryObject(exitAtError bool, v any, id string) Problem

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

func (*Context) Read added in v0.34.0

func (ctx *Context) Read(exitAtError bool, v any, id string) Problem

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

如果 v 实现了 Filter 接口,则在读取数据之后,会调用该接口方法。 如果验证失败,会返回以 id 作为错误代码的 Problem 对象。

func (*Context) Render added in v0.34.0

func (ctx *Context) Render(status int, body any)

Render 向客户端输出对象

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

func (*Context) Request added in v0.34.0

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

Request 返回原始的请求对象

func (*Context) RequestBody added in v0.83.0

func (ctx *Context) RequestBody() io.Reader

RequestBody 用户提交的内容

func (*Context) Route added in v0.83.0

func (ctx *Context) Route() types.Route

Route 关联的路由信息

func (*Context) Server added in v0.34.0

func (ctx *Context) Server() Server

Server 获取关联的 Server 实例

func (*Context) SetCharset added in v0.83.0

func (ctx *Context) SetCharset(charset string)

SetCharset 设置输出的字符集

相当于重新设置了 Context.Request 的 Accept-Charset 报头,但是不会实际修改 Context.Request

func (*Context) SetCookies added in v0.83.0

func (ctx *Context) SetCookies(c ...*http.Cookie)

SetCookies 输出一组 Cookie

func (*Context) SetEncoding added in v0.83.0

func (ctx *Context) SetEncoding(enc string)

SetEncoding 设置输出的压缩编码

func (*Context) SetLanguage added in v0.83.0

func (ctx *Context) SetLanguage(tag language.Tag)

SetLanguage 修改输出的语言

相当于重新设置了 Context.Request 的 Accept-Language 报头,但是不会实际修改 Context.Request

func (*Context) SetMimetype added in v0.83.0

func (ctx *Context) SetMimetype(mimetype string)

SetMimetype 设置输出的格式

相当于重新设置了 Context.Request 的 Accept 报头,但是不会实际修改 Context.Request

func (*Context) SetVar added in v0.83.0

func (ctx *Context) SetVar(key, val any)

SetVar 设置变量

func (*Context) Sprintf added in v0.34.0

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

Sprintf 将内容翻译成当前请求的语言

func (*Context) Unmarshal added in v0.34.0

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

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

func (*Context) Unwrap added in v0.83.0

func (ctx *Context) Unwrap() http.ResponseWriter

Unwrap http.ResponseController 通过此方法返回底层的 http.ResponseWriter

func (*Context) Wrap added in v0.86.0

func (ctx *Context) Wrap(f func(http.ResponseWriter) http.ResponseWriter)

Wrap 替换底层的 http.ResponseWriter 对象

f 用于构建新的 http.ResponseWriter 对象,其原型为:

func(w http.ResponseWriter) http.ResponseWriter

其中 w 表示原本与 Context 关联的对象,返回一个新的替换对象。 如果已经有内容输出,此操作将会 panic。

func (*Context) Write added in v0.83.0

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

Write 向客户端输出内容

如非必要,应该采用 Context.Render 输出。

func (*Context) WriteHeader added in v0.83.0

func (ctx *Context) WriteHeader(status int)

WriteHeader 向客户端输出 HTTP 状态码

如非必要,应该通过 Context.Render 输出。

func (*Context) Wrote added in v0.83.0

func (ctx *Context) Wrote() bool

Wrote 是否已经有内容输出

type ContextBuilder added in v0.86.0

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

ContextBuilder 用于创建 Context

func NewContextBuilder added in v0.86.0

func NewContextBuilder(s Server, codec *Codec, requestIDKey string) *ContextBuilder

NewContextBuilder 声明 ContextBuilder

requestIDKey 表示客户端提交的 X-Request-ID 报头名,如果为空则采用 "X-Request-ID";

func (*ContextBuilder) NewContext added in v0.86.0

func (b *ContextBuilder) NewContext(w http.ResponseWriter, r *http.Request, route types.Route) *Context

NewContext 将 w 和 r 包装为 Context 对象

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

type FieldError added in v0.66.1

type FieldError = config.FieldError

FieldError 表示配置文件中的字段错误

func NewFieldError added in v0.66.1

func NewFieldError(field string, msg any) *FieldError

NewFieldError 返回表示配置文件错误的对象

field 表示错误的字段名; msg 表示错误信息,可以是任意类型,如果 msg 是 FieldError 类型, 那么此操作相当于调用了 [FieldError.AddFieldParent];

type Filter added in v0.33.0

type Filter interface {
	Filter(*FilterContext)
}

Filter 用户提交数据的验证修正接口

type FilterContext added in v0.86.0

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

FilterContext 处理由过滤器生成的各错误

func (*FilterContext) Add added in v0.86.0

Add 添加由过滤器 f 返回的错误信息

func (*FilterContext) AddError added in v0.86.0

func (v *FilterContext) AddError(name string, err error) *FilterContext

AddError 直接添加一条类型为 error 的错误信息

func (*FilterContext) AddFilter added in v0.86.0

func (v *FilterContext) AddFilter(name string, f Filter) *FilterContext

AddFilter 验证实现了 Filter 接口的对象

func (*FilterContext) AddReason added in v0.86.0

func (v *FilterContext) AddReason(name string, reason LocaleStringer) *FilterContext

AddReason 直接添加一条错误信息

func (*FilterContext) Context added in v0.86.0

func (v *FilterContext) Context() *Context

Context 返回关联的 Context 实例

func (*FilterContext) New added in v0.86.0

func (v *FilterContext) New(name string, f func(f *FilterContext)) *FilterContext

New 声明验证的子对象

name 为 f 中验证对象的整体名称; f 为验证方法,其原型为 func(fp *FilterContext) 往 fp 写入的信息,其字段名均会以 name 作为前缀写入到当前对象 v 中。 fp 的各种属性均继承自 v。

func (*FilterContext) Problem added in v0.86.0

func (v *FilterContext) Problem(id string) Problem

Problem 如果有错误信息转换成 Problem 否则返回 nil

func (*FilterContext) When added in v0.86.0

func (v *FilterContext) When(cond bool, f func(v *FilterContext)) *FilterContext

When 只有满足 cond 才执行 f 中的验证

f 中的 v 即为当前对象;

type FilterFunc added in v0.86.0

type FilterFunc = func() (string, LocaleStringer)

FilterFunc 过滤器

当前方法由 FilterFuncOf 生成,验证的数据也由其提供, 但是只有在调用当前方法时才真正对数据进行验证。 如果符合要求返回 "", nil,否则返回字段名和错误信息。

FilterFunc 与其它各个的关系如下:

                              |---[Sanitize]
                              |
[FilterFunc]---[FilterFuncOf]-|---[RuleFuncOf]-|---[LocaleStringer]
                                               |
                                               |---[Validator]

调用者可以提前声明 FilterFuncOf 实例,在需要时调用 FilterFuncOf 实例, 生成一个类型无关的方法 FilterFunc 传递给 FilterContext。 这样可以绕过 Go 不支持泛型方法的尴尬。

Sanitize 表示对数据的修正,其函数原型为:func(*T) 指针传入数据,实现方可以对指向的数据进行修改。sanitizer 提供了一些通用的实现;

Validator 负责验证数据,其原型为:func(T)bool 返回值表示是否符合当前函数的需求。validator 提供了一些通用的实现;

RuleFuncOf 这是验证器与提示信息的结合,当不符合当前规则所包含的验证器需求时,返回对应的错误信息。

type FilterFuncOf added in v0.86.0

type FilterFuncOf[T any] func(name string, v *T) FilterFunc

FilterFuncOf 生成某数值的过滤器

name 字段名,对于切片等类型会返回带下标的字段名; v 必须是指针类型,否则无法对其内容进行修改;

func NewFilter added in v0.74.0

func NewFilter[T any](rule RuleFuncOf[T], s ...func(*T)) FilterFuncOf[T]

NewFilter 生成 FilterFuncOf

s 表示对字段 v 的一些清理,比如去除空白字符等,如果指定了此参数,会在 rule 之前执行;

func NewFilterFromVS added in v0.86.0

func NewFilterFromVS[T any](msg LocaleStringer, v func(T) bool, s ...func(*T)) FilterFuncOf[T]

NewFilterFromVS 生成 FilterFuncOf

msg 和 v 组成验证规则; s 表示对字段 v 的一些清理,比如去除空白字符等,如果指定了此参数,会在 rule 之前执行;

func NewMapFilter added in v0.86.0

func NewMapFilter[K comparable, V any, M ~map[K]V](rule RuleFuncOf[V], s ...func(*V)) FilterFuncOf[M]

NewMapFilter 生成针对 map 元素的 FilterFuncOf

rule 和 s 将会应用到每个元素 T 上。

func NewSliceFilter added in v0.86.0

func NewSliceFilter[T any, S ~[]T](rule RuleFuncOf[T], s ...func(*T)) FilterFuncOf[S]

NewSliceFilter 生成针对切片元素的 FilterFuncOf

rule 和 s 将会应用到每个元素 T 上。

type HandlerFunc added in v0.33.0

type HandlerFunc = func(*Context) Responser

HandlerFunc 路由的处理函数原型

向客户端输出内容的有两种方法,一种是通过 Context.Write 方法; 或是返回 Responser 对象。前者在调用 Context.Write 时即输出内容, 后者会在整个请求退出时才将 Responser 进行编码输出。

返回值可以为空,表示在中间件执行过程中已经向客户端输出同内容。

type JobFunc added in v0.33.0

type JobFunc = scheduled.JobFunc

type Locale added in v0.41.0

type Locale interface {
	catalog.Catalog

	// ID 返回默认的语言标签
	ID() language.Tag

	// LoadMessages 从 fsys 中加载符合 glob 的本地化文件
	//
	// 根据 [Server.Config] 处理文件格式,如果文件格式不被 [Server.Config] 支持,将无法加载。
	LoadMessages(glob string, fsys ...fs.FS) error

	// Printer 最符合 [Locale.ID] 的 [message.Printer] 对象
	Printer() *message.Printer

	// Sprintf 等同于 Locale.Printer.Sprintf
	Sprintf(string, ...any) string

	// NewPrinter 声明最符合 tag 的 [message.Printer] 对象
	//
	// NOTE: 每当给 [Locale.SetString]、[Locale.SetMacro] 和 [Locale.Set] 传递新的 [language.Tag]
	// 值时,可能造成 NewPrinter 相同的入参而返回不同的返回对象的情况。
	NewPrinter(tag language.Tag) *message.Printer

	// SetString 添加新的翻译项
	//
	// 功能同 [catalog.Builder.SetString]
	SetString(tag language.Tag, key, msg string) error

	// SetMacro 添加新的翻译项
	//
	// 功能同 [catalog.Builder.SetMacro]
	SetMacro(tag language.Tag, name string, msg ...catalog.Message) error

	// Set 添加新的翻译项
	//
	// 功能同 [catalog.Builder.Set]
	Set(tag language.Tag, key string, msg ...catalog.Message) error
}

Locale 提供与本地化相关的功能

type LocaleProblem added in v0.86.0

type LocaleProblem struct {
	ID            string
	Title, Detail LocaleStringer
}

type LocaleStringer added in v0.43.0

type LocaleStringer = localeutil.Stringer

LocaleStringer 本地化字符串需要实在的接口

func Phrase added in v0.42.0

func Phrase(key string, v ...any) LocaleStringer

Phrase 生成本地化的语言片段

type Logger added in v0.50.2

type Logger = logs.Logger

type Logs added in v0.79.0

type Logs = logs.Logs

type MarshalFunc added in v0.83.0

type MarshalFunc = func(*Context, any) ([]byte, error)

MarshalFunc 序列化函数原型

NOTE: MarshalFunc 的作用是输出内容,所以在实现中不能调用 Context.Render 等输出方法。

NOTE: 不采用流的方式处理数据原原因是因为,编码过程中可能会出错, 此时需要修改状态码,流式的因为有内容输出,状态码也已经固定,无法修改。

type Middleware added in v0.33.0

type Middleware = types.MiddlewareOf[HandlerFunc]

type MiddlewareFunc added in v0.46.0

type MiddlewareFunc = types.MiddlewareFuncOf[HandlerFunc]

type Paths added in v0.83.0

type Paths FilterContext

Paths 提供对路径参数的处理

func (*Paths) Bool added in v0.83.0

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

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

strconv.ParseBool 进行转换。

func (*Paths) Float64 added in v0.83.0

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

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

func (*Paths) ID added in v0.83.0

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

ID 返回 key 所表示的值且必须大于 0

func (*Paths) Int64 added in v0.83.0

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

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

func (*Paths) Problem added in v0.83.0

func (p *Paths) Problem(id string) Problem

Problem 如果有错误信息转换成 Problem 否则返回 nil

func (*Paths) String added in v0.83.0

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

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

type Prefix added in v0.33.0

type Prefix = mux.PrefixOf[HandlerFunc]

type Problem added in v0.80.0

type Problem interface {
	Responser

	// WithParam 添加具体的错误字段及描述信息
	//
	// 如果已经存在同名,则会 panic。
	WithParam(name, reason string) Problem

	// WithExtensions 指定扩展对象信息
	//
	// 多次调用将会覆盖之前的内容。
	WithExtensions(any) Problem

	// WithInstance 指定发生错误的实例
	//
	// 多次调用将会覆盖之前的内容。
	WithInstance(string) Problem
	// contains filtered or unexported methods
}

Problem 向用户反馈非正常信息的对象接口

type Problems added in v0.86.0

type Problems interface {
	// Add 添加新项
	//
	// NOTE: 已添加的内容无法修改,如果确实有需求,
	// 只能通过修改翻译项的方式间接进行修改。
	Add(status int, p ...LocaleProblem) Problems

	// Init 将指定 ID 的项注入 [RFC7807] 对象
	Init(problem *RFC7807, id string, p *message.Printer)

	// Visit 遍历错误代码
	//
	// visit 签名:
	//
	//	func(id string, status int, title, detail LocaleStringer)
	//
	// id 为错误代码,不包含前缀部分;
	// status 该错误代码反馈给用户的 HTTP 状态码;
	// title 错误代码的简要描述;
	// detail 错误代码的明细;
	Visit(visit func(id string, status int, title, detail LocaleStringer))

	// Prefix 所有 ID 的统一前缀
	Prefix() string
}

Problems Problem 管理接口

type Queries added in v0.34.0

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

Queries 提供对查询参数的处理

func (*Queries) Bool added in v0.34.0

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

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

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

func (*Queries) Float64 added in v0.34.0

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

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

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

func (*Queries) Int added in v0.34.0

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

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

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

func (*Queries) Int64 added in v0.34.0

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

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

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

func (*Queries) Object added in v0.34.0

func (q *Queries) Object(v any)

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

具体的文档信息可以参考 Query。 如果 v 实现了 Filter 接口,则在读取数据之后,会调用该接口方法。

func (*Queries) Problem added in v0.83.0

func (q *Queries) Problem(id string) Problem

Problem 如果有错误信息转换成 Problem 否则返回 nil

func (*Queries) String added in v0.34.0

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

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

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

type QueryUnmarshaler added in v0.58.0

type QueryUnmarshaler = query.Unmarshaler

QueryUnmarshaler 对查询参数的解析接口

type RFC7807 added in v0.85.0

type RFC7807 struct {
	Type       string         `json:"type" xml:"type" form:"type"`
	Title      string         `json:"title" xml:"title" form:"title"`
	Detail     string         `json:"detail,omitempty" xml:"detail,omitempty" form:"detail,omitempty"`
	Instance   string         `json:"instance,omitempty" xml:"instance,omitempty" form:"instance,omitempty"`
	Status     int            `json:"status" xml:"status" form:"status"`
	Extensions any            `json:"extensions,omitempty" xml:"extensions,omitempty" form:"extensions,omitempty"` // 反馈给用户的信息
	Params     []RFC7807Param `json:"params,omitempty" xml:"params>i,omitempty" form:"params,omitempty"`           // 用户提交对象各个字段的错误信息
}

RFC7807 ProblemRFC7807 实现

MarshalFunc 的实现者,可能需要对 RFC7807 进行处理以便输出更加友好的格式。

func (*RFC7807) Apply added in v0.85.0

func (p *RFC7807) Apply(ctx *Context) Problem

func (*RFC7807) Error added in v0.85.0

func (p *RFC7807) Error() string

func (*RFC7807) Init added in v0.86.0

func (p *RFC7807) Init(id, title, detail string, status int)

func (*RFC7807) WithExtensions added in v0.85.0

func (p *RFC7807) WithExtensions(ext any) Problem

func (*RFC7807) WithInstance added in v0.85.0

func (p *RFC7807) WithInstance(instance string) Problem

func (*RFC7807) WithParam added in v0.85.0

func (p *RFC7807) WithParam(name, reason string) Problem

type RFC7807Param added in v0.85.0

type RFC7807Param struct {
	Name   string `json:"name" xml:"name" form:"name"`       // 出错字段的名称
	Reason string `json:"reason" xml:"reason" form:"reason"` // 出错信息
}

type Resource added in v0.33.0

type Resource = mux.ResourceOf[HandlerFunc]

type Responser added in v0.40.0

type Responser interface {
	// Apply 通过 [Context] 将当前内容渲染到客户端
	//
	// 如果执行过程出现问题可返回 [Problem] 对象作为错误信息的描述。
	//
	// 在调用 Apply 之后,就不再使用 [Responser] 对象。
	// 如果你的对象支持 [sync.Pool] 的复用方式,可以在此方法中回收内存。
	Apply(*Context) Problem
}

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

func Created added in v0.43.0

func Created(v any, location string) Responser

func KeepAlive added in v0.85.0

func KeepAlive(ctx context.Context) Responser

KeepAlive 保持当前会话不退出

func NoContent added in v0.43.0

func NoContent() Responser

func NotModified added in v0.71.0

func NotModified(etag func() (string, bool), body func() (any, error)) Responser

NotModified 决定何时可返回 304 状态码

etag 返回当前内容关联的 ETag 报头内容,其原型为:

func()(etag string, weak bool)

etag 表示对应的 etag 报头,需要包含双绰号,但是不需要 W/ 前缀,weak 是否为弱验证。

body 获取返回给客户端的报文主体对象, 如果返回的是 []byte 类型,会原样输出, 其它类型则按照 Context.Marshal 进行转换成 []byte 之后输出。

func OK added in v0.44.0

func OK(v any) Responser

OK 返回 200 状态码下的对象

func Redirect added in v0.49.0

func Redirect(status int, url string) Responser

Redirect 重定向至新的 URL

func Response added in v0.48.0

func Response(status int, body any, kv ...string) Responser

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

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

func Status added in v0.40.0

func Status(code int, kv ...string) Responser

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

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

NOTE: 即使 code 为 400 等错误代码,当前函数也不会返回 Problem 对象。

type ResponserFunc added in v0.56.0

type ResponserFunc func(*Context) Problem

func (ResponserFunc) Apply added in v0.83.0

func (f ResponserFunc) Apply(c *Context) Problem

type Router added in v0.34.0

type Router = mux.RouterOf[HandlerFunc]

type RouterMatcher added in v0.83.0

type RouterMatcher = group.Matcher

type RouterOption added in v0.83.0

type RouterOption = mux.Option

type RuleFuncOf added in v0.86.0

type RuleFuncOf[T any] func(string, T) (string, LocaleStringer)

RuleFuncOf 数据验证规则

这是验证器与错误信息的组合。

传递参数为字段名与需要验证的值; 返回字段名和错误信息,如果验证成功,则返回两个空值;

func NewMapRule added in v0.86.0

func NewMapRule[K comparable, V any, M ~map[K]V](v func(V) bool, msg LocaleStringer) RuleFuncOf[M]

NewMapRule 声明验证 map 元素的规则

func NewMapRules added in v0.86.0

func NewMapRules[K comparable, V any, M ~map[K]V](r ...RuleFuncOf[V]) RuleFuncOf[M]

func NewRule added in v0.53.1

func NewRule[T any](v func(T) bool, msg LocaleStringer) RuleFuncOf[T]

func NewRules added in v0.86.0

func NewRules[T any](r ...RuleFuncOf[T]) RuleFuncOf[T]

NewRules 将多个规则合并为一个

按顺序依次验证,直接碰到第一个验证不过的。

func NewSliceRule added in v0.86.0

func NewSliceRule[T any, S ~[]T](v func(T) bool, msg LocaleStringer) RuleFuncOf[S]

NewSliceRule 声明用于验证切片元素的规则

func NewSliceRules added in v0.86.0

func NewSliceRules[T any, S ~[]T](r ...RuleFuncOf[T]) RuleFuncOf[S]

type Scheduler added in v0.27.0

type Scheduler = scheduled.Scheduler

type SchedulerFunc added in v0.28.0

type SchedulerFunc = scheduled.SchedulerFunc

type Selector added in v0.86.0

type Selector interface {
	// Next 返回下一个可用的服务节点地址
	//
	// 返回值应该是一个有效的 URL,且要满足以下条件:
	//  - 不能以 / 结尾;
	//  - 不包含查询参数及 fragment;
	// 比如 https://example.com:8080/s1、/path。
	Next() string
}

Selector 对远程服务节点的选择接口

func RingSelector added in v0.86.0

func RingSelector(u ...string) Selector

RingSelector 一组 url 循环调用的 Selector 对象

func URLSelector added in v0.86.0

func URLSelector(u string) Selector

URLSelector 单个 URL 组成的 Selector 接口

type SelectorFunc added in v0.86.0

type SelectorFunc func() string

func (SelectorFunc) Next added in v0.86.0

func (s SelectorFunc) Next() string

type Server added in v0.25.0

type Server interface {
	// Name 应用的名称
	Name() string

	// Version 应用的版本
	Version() string

	// State 获取当前的状态
	State() State

	// Vars 操纵共享变量的接口
	Vars() *sync.Map

	// Location 服务器的时区信息
	Location() *time.Location

	// Cache 返回缓存的相关接口
	//
	// 如果要获得缓存的底层驱动接口,可以将类型转换为 [cache.Driver],
	// 该类型提供了 [cache.Driver.Driver] 方法可以获得相应的对象。
	Cache() cache.Cleanable

	// Uptime 当前服务的运行时间
	Uptime() time.Time

	// UniqueID 生成唯一性的 ID
	UniqueID() string

	// Now 返回当前时间
	//
	// 与 [time.Now] 的区别在于 Now() 基于当前时区
	Now() time.Time

	// ParseTime 分析基于当前时区的时间
	ParseTime(layout, value string) (time.Time, error)

	// Serve 开始 HTTP 服务
	//
	// 这是个阻塞方法,会等待 [Server.Close] 执行完之后才返回。
	// 始终返回非空的错误对象,如果是被 [Server.Close] 关闭的,也将返回 [http.ErrServerClosed]。
	Serve() (err error)

	// Close 触发关闭服务事件
	//
	// 需要等到 [Server.Serve] 返回才表示服务结束。
	// 调用此方法表示 [Server] 的生命周期结束,对象将处于不可用状态。
	Close(shutdownTimeout time.Duration)

	// OnClose 注册关闭服务时需要执行的函数
	//
	// NOTE: 按注册的相反顺序执行。
	OnClose(f ...func() error)

	// Config 当前项目配置文件的管理
	Config() *config.Config

	// Logs 日志接口
	Logs() Logs

	// GetRouter 获取指定名称的路由
	GetRouter(name string) *Router

	// NewRouter 声明新路由
	NewRouter(name string, matcher RouterMatcher, o ...RouterOption) *Router

	// RemoveRouter 删除路由
	RemoveRouter(name string)

	// Routers 返回所有的路由
	Routers() []*Router

	// UseMiddleware 对所有的路由使用中间件
	UseMiddleware(m ...Middleware)

	// NewContext 从标准库的参数初始化 Context 对象
	//
	// NOTE: 这适合从标准库的请求中创建 [web.Context] 对象,
	// 但是部分功能会缺失,比如地址中的参数信息,以及 [Context.Route] 等。
	NewContext(w http.ResponseWriter, r *http.Request) *Context

	// NewClient 基于当前对象的 [Server.Codec] 初始化 [Client]
	NewClient(client *http.Client, selector Selector, marshalName string, marshal func(any) ([]byte, error)) *Client

	// SetCompress 设置压缩功能
	//
	// 在服务器性能吃紧的情况下可以采用此方法禁用压缩。
	//
	// NOTE: 仅对输出内容启作用,读取内容始终是按照提交的 Content-Encoding 指定算法进行解析。
	SetCompress(enable bool)

	// CanCompress 当前是否拥有压缩功能
	CanCompress() bool

	// Problems Problem 管理
	Problems() Problems

	// Services 服务管理接口
	Services() Services

	// Locale 提供本地化相关功能
	Locale() Locale
}

Server 服务接口

type Service added in v0.25.0

type Service interface {
	// Serve 运行服务
	//
	// 这是个阻塞方法,实现者需要正确处理 [context.Context.Done] 事件。
	// 如果是通过 [context.Context] 的相关操作取消的,应该返回 [context.Context.Err]。
	Serve(context.Context) error
}

Service 长期运行的服务需要实现的接口

type ServiceFunc added in v0.25.3

type ServiceFunc func(context.Context) error

func (ServiceFunc) Serve added in v0.83.0

func (f ServiceFunc) Serve(ctx context.Context) error

type Services added in v0.25.0

type Services interface {
	// Add 添加并运行新的服务
	//
	// title 是对该服务的简要说明;
	Add(title LocaleStringer, f Service)

	// AddFunc 将函数 f 作为服务添加并运行
	AddFunc(title LocaleStringer, f func(context.Context) error)

	// AddCron 添加新的定时任务
	//
	// title 是对该服务的简要说明;
	// spec cron 表达式,支持秒;
	// delay 是否在任务执行完之后,才计算下一次的执行时间点。
	//
	// NOTE: 此功能依赖 [Server.UniqueID]。
	AddCron(title LocaleStringer, f JobFunc, spec string, delay bool)

	// AddAt 添加在某个时间点执行的任务
	//
	// title 是对该服务的简要说明;
	// at 指定的时间点;
	// delay 是否在任务执行完之后,才计算下一次的执行时间点。
	//
	// NOTE: 此功能依赖 [Server.UniqueID]。
	AddAt(title LocaleStringer, job JobFunc, at time.Time, delay bool)

	// AddJob 添加新的计划任务
	//
	// title 是对该服务的简要说明;
	// scheduler 计划任务的时间调度算法实现;
	// delay 是否在任务执行完之后,才计算下一次的执行时间点。
	//
	// NOTE: 此功能依赖 [Server.UniqueID]。
	AddJob(title LocaleStringer, job JobFunc, scheduler Scheduler, delay bool)

	// AddTicker 添加新的定时任务
	//
	// title 是对该服务的简要说明;
	// dur 时间间隔;
	// imm 是否立即执行一次该任务;
	// delay 是否在任务执行完之后,才计算下一次的执行时间点。
	//
	// NOTE: 此功能依赖 [Server.UniqueID]。
	AddTicker(title LocaleStringer, job JobFunc, dur time.Duration, imm, delay bool)

	// Visit 访问所有的服务
	//
	// visit 的原型为:
	//  func(title LocaleStringer, state State, err error)
	//
	// title 为服务的说明;
	// state 为服务的当前状态;
	// err 只在 state 为 [Failed] 时才有的错误说明;
	Visit(visit func(title LocaleStringer, state State, err error))

	// VisitJobs 访问所有的计划任务
	//
	// visit 原型为:
	//  func(title LocaleStringer, prev, next time.Time, state State, delay bool, err error)
	// title 为计划任务的说明;
	// prev 和 next 表示任务的上一次执行时间和下一次执行时间;
	// state 表示当前的状态;
	// delay 表示该任务是否是执行完才开始计算下一次任务时间的;
	// err 表示这个任务的出错状态;
	VisitJobs(visit func(LocaleStringer, time.Time, time.Time, State, bool, error))
}

Services 服务管理接口

type State added in v0.83.0

type State = scheduled.State

State 服务状态

以下设置用于 restdoc

@type string @enum stopped running failed

type StringPhrase added in v0.78.0

type StringPhrase = localeutil.StringPhrase

type UnmarshalFunc added in v0.83.0

type UnmarshalFunc = func(io.Reader, any) error

UnmarshalFunc 反序列化函数原型

参数 io.Reader 必定不会为空。

Directories

Path Synopsis
Package app 提供了简便的方式初始化 [web.Server]
Package app 提供了简便的方式初始化 [web.Server]
Package cache 统一的缓存系统接口
Package cache 统一的缓存系统接口
caches
Package caches 内置的缓存接口实现
Package caches 内置的缓存接口实现
cachetest
Package cachetest 缓存的测试用例
Package cachetest 缓存的测试用例
cmd
web module
codec
compressor
Package compressor 提供了 [web.Compressor] 的实现
Package compressor 提供了 [web.Compressor] 的实现
mimetype/file
Package file 提供与文件上下载相关的功能
Package file 提供与文件上下载相关的功能
mimetype/form
Package form 用于处理 www-form-urlencoded 编码
Package form 用于处理 www-form-urlencoded 编码
mimetype/html
Package html 提供输出 HTML 内容的解码函数
Package html 提供输出 HTML 内容的解码函数
mimetype/json
Package json JSON 格式的序列化方法
Package json JSON 格式的序列化方法
mimetype/jsonp
Package jsonp JSONP 序列化操作
Package jsonp JSONP 序列化操作
mimetype/nop
Package nop 提供了空的序列化方法
Package nop 提供了空的序列化方法
mimetype/sse
Package sse SSE 的实现 [SSE]: https://html.spec.whatwg.org/multipage/server-sent-events.html
Package sse SSE 的实现 [SSE]: https://html.spec.whatwg.org/multipage/server-sent-events.html
mimetype/xml
Package xml XML 编码的序列化操作
Package xml XML 编码的序列化操作
Package comptime 提供了编译期相关的处理方式
Package comptime 提供了编译期相关的处理方式
internal
dev
Package dev Development 环境下的功能实现
Package dev Development 环境下的功能实现
errs
Package errs 与错误相关的定义
Package errs 与错误相关的定义
header
Package header 与报头相关的处理方法
Package header 与报头相关的处理方法
locale
Package locale 用于处理本地化文件的加载
Package locale 用于处理本地化文件的加载
status
Package status 用于处理与状态码相关的功能
Package status 用于处理与状态码相关的功能
Package locales 为 web 包提供了本地化的内容
Package locales 为 web 包提供了本地化的内容
Package logs 日志操作
Package logs 日志操作
Package server 服务端实现
Package server 服务端实现
servertest
Package servertest 为 [web.Server] 提供一些简便的测试方
Package servertest 为 [web.Server] 提供一些简便的测试方

Jump to

Keyboard shortcuts

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