fastapi

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 22, 2023 License: MIT Imports: 29 Imported by: 3

README

FastApi-Golang

  • FastApiGolang实现;
  • 基于Fiber;

Usage:

go get https://github.com/Chendemo12/fastapi
查看在线文档
# 安装godoc
go install golang.org/x/tools/cmd/godoc@latest
godoc -http=:6060

# 或:pkgsite 推荐
go install golang.org/x/pkgsite/cmd/pkgsite@latest
cd fastapi-go/
pkgsite -http=:6060 -list=false
# 浏览器打开:http://127.0.0.1:6060/github.com/Chendemo12/fastapi
struct内存对齐
go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest

fieldalignment -fix ./... 
打包静态资源文件
# 安装工具
go get -u github.com/go-bindata/go-bindata/...

# 下载资源文件
#https://fastapi.tiangolo.com/img/favicon.png
#https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui.css
#https://cdn.jsdelivr.net/npm/swagger-ui-dist@4/swagger-ui-bundle.js
#https://cdn.jsdelivr.net/npm/redoc@next/bundles/redoc.standalone.js

# 打包资源文件到openapi包
go-bindata -o internal/openapi/css.go --pkg openapi internal/static/...

Examples:

Guide

一些常用的API

Documentation

Overview

Package fastapi FastApi-Python 的Golang实现

其提供了类似于FastAPI的API设计,并提供了接口文档自动生成、请求体自动校验和返回值自动序列化等使用功能;

Index

Constants

View Source
const (
	ModelNotDefine     = "Data model is undefined"
	ModelNotMatch      = "Value type mismatch"
	ModelCannotString  = "The return value cannot be a string"
	ModelCannotNumber  = "The return value cannot be a number"
	ModelCannotInteger = "The return value cannot be a integer"
	ModelCannotBool    = "The return value cannot be a boolean"
	ModelCannotArray   = "The return value cannot be a array"
	PathPsIsEmpty      = "Path must not be empty"
	QueryPsIsEmpty     = "Query must not be empty"
)
View Source
const (
	Version   = "0.1.1"
	Copyright = "chendemo12"
	Website   = "https://github.com/Chendemo12"
)
View Source
const ReminderWhenResponseModelIsNil = " `| 路由未明确定义返回值,文档处缺省为string类型,实际可以是任意类型`"
View Source
const RouteSeparator = "|_0#0_|"

RouteSeparator 路由分隔符,用于分割路由方法和路径

View Source
const WebsocketMethod = "WS"

Variables

View Source
var (
	Str    = godantic.String
	String = godantic.String

	Bool    = godantic.Bool
	Boolean = godantic.Bool

	Int    = godantic.Int
	Byte   = godantic.Uint8
	Int8   = godantic.Int8
	Int16  = godantic.Int16
	Int32  = godantic.Int32
	Int64  = godantic.Int64
	Uint8  = godantic.Uint8
	Uint16 = godantic.Uint16
	Uint32 = godantic.Uint32
	Uint64 = godantic.Uint64

	Float   = godantic.Float
	Float32 = godantic.Float32
	Float64 = godantic.Float64

	List    = godantic.List
	Array   = godantic.List
	Ints    = godantic.List(godantic.Int)
	Bytes   = godantic.List(godantic.Uint8)
	Strings = godantic.List(godantic.String)
	Floats  = godantic.List(godantic.Float)
)
View Source
var (
	StructReflect     = godantic.StructReflect
	QueryJsonName     = godantic.QueryJsonName
	IsFieldRequired   = godantic.IsFieldRequired
	ReflectObjectType = godantic.ReflectObjectType
	StringsToInts     = godantic.StringsToInts
	StringsToFloats   = godantic.StringsToFloats
)

Functions

func CombinePath

func CombinePath(prefix, path string) string

CombinePath 合并路由

@param	prefix	string	路由前缀
@param	path	string	路由

func DoesPathParamsFound

func DoesPathParamsFound(path string) (map[string]bool, bool)

DoesPathParamsFound 是否查找到路径参数

@param	path	string	路由

Types

type BaseModel

type BaseModel = godantic.BaseModel

type BaseModelIface

type BaseModelIface = godantic.Iface

type Context

type Context struct {
	PathFields  map[string]string `json:"path_fields,omitempty"`  // 路径参数
	QueryFields map[string]string `json:"query_fields,omitempty"` // 查询参数
	RequestBody any               `json:"request_body,omitempty"` // 请求体,初始值为1
	// contains filtered or unexported fields
}

Context 路由上下文信息, 也是钩子函数的操作句柄

此结构体内包含了相应体 response 以减少在路由处理过程中的内存分配和复制

注意: 当一个路由被执行完毕时, 路由函数 HandlerFunc 中的 Context 将被立刻释放回收, 因此在return之后对

Context 的任何引用都是不对的, 若需在return之后监听 Context.DisposableCtx() 则应该显式的复制或派生

func (*Context) AdvancedResponse

func (c *Context) AdvancedResponse(statusCode int, content fiber.Handler) *Response

AdvancedResponse 高级返回值,允许返回一个函数,以实现任意类型的返回 (不校验返回值)

@param	statusCode	int				响应状态码
@param	content		fiber.Handler	钩子函数
@return	resp *Response response返回体

func (*Context) AnyResponse

func (c *Context) AnyResponse(statusCode int, content any, contentType string) *Response

AnyResponse 自定义响应体,响应体可是任意类型 (不校验返回值)

@param	statusCode	int		响应状态码
@param	content		any		响应体
@param	contentType	string	响应头MIME
@return	resp *Response response返回体

func (*Context) BodyParser

func (c *Context) BodyParser(a any) *Response

BodyParser 序列化请求体

@param	c	*fiber.Ctx	fiber上下文
@param	a	any			请求体指针
@return	*Response 错误信息,若为nil 则序列化成功

func (*Context) DisposableCtx

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

DisposableCtx 针对此次请求的唯一context, 当路由执行完毕返回时,将会自动关闭

@return	context.Context 唯一context

func (*Context) Done

func (c *Context) Done() <-chan struct{}

Done 监听 DisposableCtx 是否完成退出

@return	chan struct{} 是否退出

func (*Context) EngineCtx

func (c *Context) EngineCtx() *fiber.Ctx

EngineCtx 获取web引擎的上下文 Service

@return	*fiber.Ctx fiber.App 的上下文信息

func (*Context) ErrorResponse

func (c *Context) ErrorResponse(content any) *Response

ErrorResponse 返回一个服务器错误 (不校验返回值)

@param	content	any	错误消息
@return	resp *Response response返回体

func (*Context) F

func (c *Context) F(s ...string) string

F 合并字符串

func (*Context) FileResponse

func (c *Context) FileResponse(filepath string) *Response

FileResponse 返回值为文件对象,如:照片视频文件流等, 若文件不存在,则状态码置为404 (不校验返回值)

@param	filepath	string	文件路径
@return	resp *Response response返回体

func (*Context) HTMLResponse

func (c *Context) HTMLResponse(statusCode int, context string) *Response

HTMLResponse 返回一段HTML文本 (不校验返回值)

@param	statusCode	int		响应状态码
@param	content		string	HTML文本字符串
@return	resp *Response response返回体

func (*Context) JSONResponse

func (c *Context) JSONResponse(statusCode int, content any) *Response

JSONResponse 仅支持可以json序列化的响应体 (校验返回值)

对于结构体类型: 其返回值为序列化后的json 对于基本数据类型: 其返回值为实际数值 对于数组类型: 若其子元素为Uint8,则自动转换为 StreamResponse 以避免转义错误,但应显式的返回 StreamResponse

@param	statusCode	int	响应状态码
@param	content		any	可以json序列化的类型
@return	resp *Response response返回体

func (*Context) Logger

func (c *Context) Logger() logger.Iface

Logger 获取日志句柄

func (*Context) Marshal

func (c *Context) Marshal(obj any) ([]byte, error)

func (*Context) OKResponse

func (c *Context) OKResponse(content any) *Response

OKResponse 返回状态码为200的 JSONResponse (校验返回值)

@param	content	any	可以json序列化的类型
@return	resp *Response response返回体

func (*Context) Service

func (c *Context) Service() *Service

Service 获取 FastApi 的 Service 服务依赖信息

@return	Service 服务依赖信息

func (*Context) ShouldBindJSON

func (c *Context) ShouldBindJSON(stc any) *Response

ShouldBindJSON 绑定并校验参数是否正确

func (*Context) StreamResponse

func (c *Context) StreamResponse(reader io.Reader, mime ...string) *Response

StreamResponse 返回值为字节流对象 (不校验返回值)

@param	reader	io.Reader	字节流
@param	mime	string		返回头媒体资源类型信息,	缺省则为	"text/plain"
@return	resp *Response response返回体

func (*Context) StringResponse

func (c *Context) StringResponse(content string) *Response

StringResponse 返回值为字符串对象 (校验返回值)

@param	content	string	字符串文本
@return	resp *Response response返回体

func (*Context) Unmarshal

func (c *Context) Unmarshal(data []byte, v interface{}) error

func (*Context) UserSVC

func (c *Context) UserSVC() UserService

UserSVC 获取自定义服务依赖

func (*Context) Validate

func (c *Context) Validate(stc any, ctx ...map[string]any) *Response

Validate 结构体验证

@param	stc	any	需要校验的结构体
@param	ctx	any	当校验不通过时需要返回给客户端的附加信息,仅第一个有效
@return

func (*Context) Validator

func (c *Context) Validator() *validator.Validate

Validator 获取请求体验证器

type CronJob

type CronJob interface {
	// String 可选的任务文字描述
	String() string
	// Interval 任务执行间隔, 调度协程会在此时间间隔内循环触发 Do 任务, 任务的触发间隔不考虑任务的执行时间
	Interval() time.Duration
	// Do 定时任务, 每 Interval 个时间间隔都将触发此任务,即便上一个任务可能因超时未执行完毕.
	// 其中 Do 的执行耗时应 <= Interval 本身, 否则将视为超时, 超时将触发 WhenTimeout
	Do(ctx context.Context) error
	// WhenError 当 Do 执行失败时触发的回调, 若 Do 执行失败且超时, 则 WhenError 和 WhenTimeout
	// 将同时被执行
	WhenError(errs ...error)
	// WhenTimeout 当定时任务未在规定时间内执行完毕时触发的回调, 当上一次 Do 执行超时时, 此 WhenTimeout 将和
	// Do 同时执行, 即 Do 和 WhenError 在同一个由 WhenTimeout 创建的子协程内。
	WhenTimeout()
}

type Ctx

type Ctx = Context

type Dict

type Dict = map[string]any // python.Dict

type DictIface

type DictIface = godantic.DictIface

type Event

type Event struct {
	Fc   func()
	Type EventKind // 事件类型:startup 或 shutdown
}

type EventKind

type EventKind string

type FastApi

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

func New

func New(title, version string, debug bool, svc UserService) *FastApi

New 创建一个 FastApi 服务

@param	title	string		Application	name
@param	version	string		Version
@param	debug	bool		是否开启调试模式
@param	service	UserService	custom	ServiceContext
@return	*FastApi fastapi对象

func (*FastApi) APIRouters

func (f *FastApi) APIRouters() []*Router

APIRouters 获取全部注册的路由组

@return	[]*Router 路由组

func (*FastApi) AcquireCtx

func (f *FastApi) AcquireCtx(fctx *fiber.Ctx) *Context

AcquireCtx 申请一个 Context 并初始化

func (*FastApi) ActivateHotSwitch

func (f *FastApi) ActivateHotSwitch() *FastApi

ActivateHotSwitch 创建一个热开关,监听信号量30,用来改变程序调试开关状态

func (*FastApi) AddCronjob

func (f *FastApi) AddCronjob(jobs ...CronJob) *FastApi

AddCronjob 添加定时任务(循环调度任务) 此任务会在各种初始化及启动事件全部执行完成之后触发

func (*FastApi) AddResponseHeader

func (f *FastApi) AddResponseHeader(key, value string) *FastApi

AddResponseHeader 添加一个响应头

@param	key		string	键
@param	value	string	值

func (*FastApi) DeleteResponseHeader

func (f *FastApi) DeleteResponseHeader(key string) *FastApi

DeleteResponseHeader 删除一个响应头

@param	key	string	键

func (*FastApi) Description

func (f *FastApi) Description() string

Description 描述信息,同时会显示在Swagger文档上

func (*FastApi) DisableBaseRoutes

func (f *FastApi) DisableBaseRoutes() *FastApi

DisableBaseRoutes 禁用基础路由

func (*FastApi) DisableMultipleProcess

func (f *FastApi) DisableMultipleProcess() *FastApi

DisableMultipleProcess 禁用多进程

func (*FastApi) DisableRequestValidate

func (f *FastApi) DisableRequestValidate() *FastApi

DisableRequestValidate 禁用请求体自动验证

func (*FastApi) DisableResponseValidate

func (f *FastApi) DisableResponseValidate() *FastApi

DisableResponseValidate 禁用返回体自动验证

func (*FastApi) DisableSwagAutoCreate

func (f *FastApi) DisableSwagAutoCreate() *FastApi

DisableSwagAutoCreate 禁用文档自动生成

func (*FastApi) DumpPID

func (f *FastApi) DumpPID()

DumpPID 存储PID, 文件权限为0775 对于 Windows 其文件为当前运行目录下的pid.txt; 对于 类unix系统,其文件为/run/{Title}.pid, 若无读写权限则改为当前运行目录下的pid.txt;

func (*FastApi) EnableDumpPID

func (f *FastApi) EnableDumpPID() *FastApi

EnableDumpPID 启用PID存储

func (*FastApi) Engine

func (f *FastApi) Engine() *fiber.App

Engine 获取fiber引擎

@return	*fiber.App fiber引擎

func (*FastApi) Host

func (f *FastApi) Host() string

func (*FastApi) IncludeRouter

func (f *FastApi) IncludeRouter(router *Router) *FastApi

IncludeRouter 注册一个路由组

@param	router	*Router	路由组

func (*FastApi) IsDebug

func (f *FastApi) IsDebug() bool

func (*FastApi) OnEvent

func (f *FastApi) OnEvent(kind EventKind, fc func()) *FastApi

OnEvent 添加事件

@param	kind	事件类型,取值需为	"startup"	/	"shutdown"
@param	fs		func()		事件

func (*FastApi) OnShutdown

func (f *FastApi) OnShutdown(fc func()) *FastApi

OnShutdown 添加关闭事件

@param	fs	func()	事件

func (*FastApi) OnStartup

func (f *FastApi) OnStartup(fc func()) *FastApi

OnStartup 添加启动事件

@param	fs	func()	事件

func (*FastApi) PID

func (f *FastApi) PID() int

func (*FastApi) Port

func (f *FastApi) Port() string

func (*FastApi) ReleaseCtx

func (f *FastApi) ReleaseCtx(ctx *Context)

ReleaseCtx 释放并归还 Context

func (*FastApi) ReplaceErrorHandler

func (f *FastApi) ReplaceErrorHandler(fc fiber.ErrorHandler) *FastApi

ReplaceErrorHandler 替换fiber错误处理方法,是 请求错误处理方法

func (*FastApi) ReplaceRecover

func (f *FastApi) ReplaceRecover(fc StackTraceHandlerFunc) *FastApi

ReplaceRecover 重写全局 recover 方法

func (*FastApi) ReplaceStackTraceHandler

func (f *FastApi) ReplaceStackTraceHandler(fc StackTraceHandlerFunc) *FastApi

ReplaceStackTraceHandler 替换错误堆栈处理函数,即 recover 方法

func (*FastApi) Run

func (f *FastApi) Run(host, port string)

Run 启动服务, 此方法会阻塞运行,因此必须放在main函数结尾 此方法已设置关闭事件和平滑关闭. 当 Interrupt 信号被触发时,首先会关闭 根Context,然后逐步执行“关机事件”,最后调用平滑关闭方法,关闭服务 启动前通过 SetShutdownTimeout 设置"平滑关闭异常时"的最大超时时间

func (*FastApi) Service

func (f *FastApi) Service() *Service

Service 获取FastApi全局服务依赖

func (*FastApi) SetDescription

func (f *FastApi) SetDescription(description string) *FastApi

SetDescription 设置APP的详细描述信息

@param	Description	string	详细描述信息

func (*FastApi) SetLogger

func (f *FastApi) SetLogger(logger logger.Iface) *FastApi

SetLogger 替换日志句柄,此操作必须在run之前进行

@param	logger	logger.Iface	日志句柄

func (*FastApi) SetShutdownTimeout

func (f *FastApi) SetShutdownTimeout(timeout int) *FastApi

SetShutdownTimeout 修改关机前最大等待时间

@param	timeout	in	修改关机前最大等待时间,	单位秒

func (*FastApi) SetUserSVC

func (f *FastApi) SetUserSVC(svc UserService) *FastApi

SetUserSVC 设置一个自定义服务依赖

@param	service	UserService	服务依赖

func (*FastApi) Shutdown

func (f *FastApi) Shutdown()

Shutdown 平滑关闭

func (*FastApi) ShutdownWithTimeout

func (f *FastApi) ShutdownWithTimeout() time.Duration

ShutdownWithTimeout 关机前最大等待时间

func (*FastApi) Title

func (f *FastApi) Title() string

Title 应用程序名和日志文件名

func (*FastApi) Use

func (f *FastApi) Use(middleware ...any) *FastApi

Use 添加中间件

func (*FastApi) Version

func (f *FastApi) Version() string

type Field

type Field = godantic.Field

type H

type H = map[string]any // gin.H

type HTTPValidationError

type HTTPValidationError = godantic.HTTPValidationError

type HandlerFunc

type HandlerFunc = func(s *Context) *Response

HandlerFunc 路由处理函数

type Job

type Job struct{}

func (*Job) Do

func (c *Job) Do() func(ctx context.Context) error

Do 定时任务

func (*Job) Interval

func (c *Job) Interval() time.Duration

Interval 执行调度间隔

func (*Job) String

func (c *Job) String() string

String 任务文字描述

func (*Job) WhenError

func (c *Job) WhenError(errs ...error)

WhenError 当 Do 执行失败时触发的回调

func (*Job) WhenTimeout

func (c *Job) WhenTimeout()

WhenTimeout 当任务超时时执行的回调

type M

type M = map[string]any // Map

type MetaField

type MetaField = godantic.MetaField

type Metadata

type Metadata = godantic.Metadata

type Option added in v0.1.1

type Option struct {
	Params       godantic.QueryParameter `json:"params" description:"查询参数,结构体"`
	Description  string                  `json:"description" description:"路由描述"`
	Summary      string                  `json:"summary" description:"摘要描述"`
	Tags         []string                `json:"tags" description:"路由标签"`
	Dependencies []fiber.Handler         `json:"-" description:"依赖"`
	Handlers     []fiber.Handler         `json:"-" description:"处理函数"`
	Deprecated   bool                    `json:"deprecated" description:"是否禁用"`
}

type QueryModel

type QueryModel = godantic.QueryModel

type QueryParameter

type QueryParameter = godantic.QueryParameter

type Response

type Response struct {
	Content     any          `json:"content"`     // 响应体
	ContentType string       `json:"contentType"` // 响应类型,默认为 application/json
	Type        ResponseType `json:"type"`        // 返回体类型
	StatusCode  int          `json:"status_code"` // 响应状态码
}

Response 路由返回值

type ResponseHeader

type ResponseHeader struct {
	Key   string `json:"key" Description:"Key" binding:"required"`
	Value string `json:"value" Description:"Value" binding:"required"`
}

ResponseHeader 自定义响应头

type ResponseType

type ResponseType int
const (
	CustomResponseType ResponseType = iota + 1
	JsonResponseType
	StringResponseType
	StreamResponseType
	FileResponseType
	ErrResponseType
	HtmlResponseType
	AdvancedResponseType
)

type Route

type Route struct {
	ResponseModel *godantic.Metadata `description:"响应体元数据"`
	RequestModel  *godantic.Metadata `description:"请求体元数据"`

	Description  string             `json:"description" description:"详细描述"`
	Summary      string             `json:"summary" description:"摘要描述"`
	Method       string             `json:"method" description:"请求方法"`
	RelativePath string             `json:"relative_path" description:"相对路由"`
	Tags         []string           `json:"tags" description:"路由标签"`
	QueryFields  []*godantic.QModel `json:"-" description:"查询参数"`
	Handlers     []fiber.Handler    `json:"-" description:"处理函数"`
	Dependencies []HandlerFunc      `json:"-" description:"依赖"`
	PathFields   []*godantic.QModel `json:"-" description:"路径参数"`
	// contains filtered or unexported fields
}

Route 一个完整的路由对象,此对象会在程序启动时生成swagger文档 其中相对路径Path不能重复,否则后者会覆盖前者

func (*Route) AddD

func (f *Route) AddD(fcs ...HandlerFunc) *Route

AddD 添加依赖项,用于在执行路由函数前执行一个自定义操作,此操作作用于参数校验通过之后

@param	fcs	HandlerFunc	依赖项

func (*Route) AddDependency

func (f *Route) AddDependency(fcs ...HandlerFunc) *Route

AddDependency 添加依赖项,用于在执行路由函数前执行一个自定义操作,此操作作用于参数校验通过之后

@param	fcs	HandlerFunc	依赖项

func (*Route) Deprecate

func (f *Route) Deprecate() *Route

Deprecate 禁用路由

func (*Route) LowerMethod

func (f *Route) LowerMethod() string

func (*Route) NewRequestModel

func (f *Route) NewRequestModel() any

NewRequestModel 创建一个新的请求体模型

func (*Route) Path

func (f *Route) Path(prefix string) string

Path 合并路由

@param	prefix	string	路由组前缀

func (*Route) SetD

func (f *Route) SetD(description string) *Route

SetD 设置一个路由的详细描述信息

@param	Description	string	详细描述信息

func (*Route) SetDescription

func (f *Route) SetDescription(description string) *Route

SetDescription 设置一个路由的详细描述信息

@param	Description	string	详细描述信息

func (*Route) SetQ

func (f *Route) SetQ(m godantic.QueryParameter) *Route

SetQ 设置查询参数,此空struct的每一个字段都将作为一个单独的查询参数 且此结构体的任意字段有且仅支持 string 类型

@param	m	godantic.QueryParameter	查询参数对象,

func (*Route) SetQueryParams

func (f *Route) SetQueryParams(m godantic.QueryParameter) *Route

SetQueryParams 设置查询参数,此空struct的每一个字段都将作为一个单独的查询参数 且此结构体的任意字段有且仅支持 string 类型

@param	m	godantic.QueryParameter	查询参数对象,

func (*Route) SetReq

func (f *Route) SetReq(m godantic.SchemaIface) *Route

SetReq 设置请求体对象

@param	m	any	请求体对象

func (*Route) SetRequestModel

func (f *Route) SetRequestModel(m godantic.SchemaIface) *Route

SetRequestModel 设置请求体对象,此model应为一个空struct实例,而非指针类型,且仅"GET",http.MethodDelete有效

@param	m	any	请求体对象

type RouteMeta

type RouteMeta struct {
	Get    *Route
	Post   *Route
	Patch  *Route
	Delete *Route
	Put    *Route
	Any    *Route
	Path   string `json:"path" description:"绝对路由"`
}

RouteMeta 记录创建的路由对象,用于其后的请求和响应校验

type RouteModelValidateHandlerFunc added in v0.1.1

type RouteModelValidateHandlerFunc func(resp any, meta *godantic.Metadata) *Response

RouteModelValidateHandlerFunc 返回值校验方法

@param	resp	any					响应体
@param	meta	*godantic.Metadata	模型元数据
@return	*Response 响应体

type Router

type Router struct {
	Prefix string
	Tags   []string
	// contains filtered or unexported fields
}

Router 一个独立的路由组,Prefix路由组前缀,其内部的子路由均包含此前缀

func APIRouter

func APIRouter(prefix string, tags []string) *Router

APIRouter 创建一个路由组

func (*Router) Activate

func (f *Router) Activate() *Router

Activate 激活整个路由组路由

func (*Router) DELETE

func (f *Router) DELETE(
	path string, responseModel godantic.SchemaIface, summary string, handler HandlerFunc, opts ...*Option,
) *Route

DELETE http delete method

@param	path			string					相对路径,必须以"/"开头
@param	summary			string					路由摘要信息
@param	responseModel	godantic.SchemaIface	响应体对象,	此model应为一个空struct实例,而非指针类型
@param	handler			[]HandlerFunc			路由处理方法
@param	addition		any						附加参数

func (*Router) Deprecate

func (f *Router) Deprecate() *Router

Deprecate 禁用整个路由组路由

func (*Router) GET

func (f *Router) GET(
	path string,
	responseModel godantic.SchemaIface,
	summary string,
	handler HandlerFunc,
	opts ...*Option,
) *Route

GET http get method

@param	path			string					相对路径,必须以"/"开头
@param	summary			string					路由摘要信息
@param	queryModel		godantic.QueryParameter	查询参数,仅支持struct类型
@param	responseModel	godantic.SchemaIface	响应体对象,	此model应为一个空struct实例,而非指针类型
@param	handler			[]HandlerFunc			路由处理方法
@param	addition		any						附加参数,如:"deprecated"用于禁用此路由

func (*Router) IncludeRouter

func (f *Router) IncludeRouter(router *Router) *Router

IncludeRouter 挂载一个子路由组,目前仅支持在子路由组初始化后添加

@param	router	*Router	子路由组

func (*Router) PATCH

func (f *Router) PATCH(
	path string,
	requestModel, responseModel godantic.SchemaIface,
	summary string,
	handler HandlerFunc,
	opts ...*Option,
) *Route

PATCH http patch method

func (*Router) POST

func (f *Router) POST(
	path string,
	requestModel, responseModel godantic.SchemaIface,
	summary string,
	handler HandlerFunc,
	opts ...*Option,
) *Route

POST http post method

@param	path			string					相对路径,必须以"/"开头
@param	summary			string					路由摘要信息
@param	requestModel	godantic.SchemaIface	请求体对象,	此model应为一个空struct实例,而非指针类型
@param	responseModel	godantic.SchemaIface	响应体对象,	此model应为一个空struct实例,而非指针类型
@param	handler			[]HandlerFunc			路由处理方法
@param	addition		any						附加参数,如:"deprecated"用于禁用此路由

func (*Router) PUT

func (f *Router) PUT(
	path string,
	requestModel, responseModel godantic.SchemaIface,
	summary string,
	handler HandlerFunc,
	opts ...*Option,
) *Route

PUT http put method

func (*Router) Routes

func (f *Router) Routes() map[string]*Route

Routes 获取路由组内部定义的全部子路由信息

func (*Router) Websocket

func (f *Router) Websocket(path string, handler WSHandler) *Route

Websocket 创建一个 websocket 服务

type Schedule

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

func (*Schedule) AtTime

func (s *Schedule) AtTime() <-chan time.Time

AtTime 到达任务的执行时间

func (*Schedule) Cancel

func (s *Schedule) Cancel()

Cancel 取消此定时任务

func (*Schedule) Do

func (s *Schedule) Do()

Do 执行任务

func (*Schedule) Scheduler

func (s *Schedule) Scheduler()

Scheduler 当时间到达时就启动一个任务协程

func (*Schedule) String

func (s *Schedule) String() string

String 任务描述

type Scheduler

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

func NewScheduler

func NewScheduler(ctx context.Context, lg logger.Iface) *Scheduler

NewScheduler 创建一个任务调度器

@param	ctx	context.Context	根Context
@param	lg	logger.Iface	可选的日志句柄
@return	scheduler 任务调度器

# Usage
// 首先创建一个根 Context
pCtx, _ := context.WithTimeout(context.Background(), 50*time.Second)
scheduler := NewScheduler(pCtx, logger)

// 定义任务, 需实现 CronJob 接口
type Clock struct {
	Job	// 默认 Job 未实现 Do 方法
	lastTime time.Time
}

func (c *Clock) Interval() time.Duration { return 1 * time.Second }
func (c *Clock) String() string          { return "报时器" }

func (c *Clock) Do(ctx context.Context) error {
	diff := time.Now().Sub(c.lastTime)
	c.lastTime = time.Now()
	fmt.Println("time interval:", diff.String())

	return nil
}

// 注册任务
scheduler.Add(&Clock{})
// 运行调度器
scheduler.Run()
// 检测调度器是否退出
<-scheduler.Done()

func (*Scheduler) Add

func (s *Scheduler) Add(jobs ...CronJob) *Scheduler

func (*Scheduler) AddCronjob

func (s *Scheduler) AddCronjob(jobs ...CronJob) *Scheduler

AddCronjob 添加任务

func (*Scheduler) DisableMsg

func (s *Scheduler) DisableMsg() *Scheduler

DisableMsg 禁用内部日志输出

func (*Scheduler) Done

func (s *Scheduler) Done() <-chan struct{}

func (*Scheduler) QuerySchedule

func (s *Scheduler) QuerySchedule(title string) *Schedule

QuerySchedule 依据任务描述查找任务

func (*Scheduler) Run

func (s *Scheduler) Run()

Run 启动任务调度器(非阻塞)

func (*Scheduler) SetLogger

func (s *Scheduler) SetLogger(logger logger.Iface) *Scheduler

type SchemaIface

type SchemaIface = godantic.SchemaIface

type Service

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

Service FastApi 全局服务依赖信息 此对象由FastApi启动时自动创建,此对象不应被修改,组合和嵌入, 但可通过 setUserSVC 接口设置自定义的上下文信息,并在每一个路由钩子函数中可得

func (*Service) Addr

func (s *Service) Addr() string

Addr 绑定地址

@return	string 绑定地址

func (*Service) Done

func (s *Service) Done() <-chan struct{}

Done 监听程序是否退出或正在关闭,仅当程序关闭时解除阻塞

func (*Service) Logger

func (s *Service) Logger() logger.Iface

Logger 获取日志句柄

func (*Service) RootCtx

func (s *Service) RootCtx() context.Context

RootCtx 根 context

@return	context.Context 整个服务的根 context

func (*Service) Scheduler

func (s *Service) Scheduler() *Scheduler

Scheduler 获取内部调度器

func (*Service) Validate added in v0.1.1

func (s *Service) Validate(stc any, ctx ...map[string]any) *Response

Validate 结构体验证

@param	stc	any	需要校验的结构体
@param	ctx	any	当校验不通过时需要返回给客户端的附加信息,仅第一个有效
@return

type StackTraceHandlerFunc

type StackTraceHandlerFunc = func(c *fiber.Ctx, e any)

StackTraceHandlerFunc 错误堆栈处理函数, 即 recover 方法

type UserService

type UserService interface {
	Config() any // 获取配置文件
}

UserService 自定义服务依赖信息

type ValidationError

type ValidationError = godantic.ValidationError

type WSHandler

type WSHandler interface {
	OnConnected() error
	OnClosed() error
	OnReceived() error
	OnError()
}

type Websocket

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

func NewWebsocket

func NewWebsocket(point string, handler WSHandler) *Websocket

func (*Websocket) Upgrade

func (w *Websocket) Upgrade(resp http.ResponseWriter, req *http.Request, responseHeader http.Header) error

Directories

Path Synopsis
internal
constant
Package constant 关键常量
Package constant 关键常量
core
Package core 内部标志量
Package core 内部标志量
Package openapi generated by go-bindata.
Package openapi generated by go-bindata.
Package tool 常用的python标准库方法实现
Package tool 常用的python标准库方法实现
Package websocket implements the WebSocket protocol defined in RFC 6455.
Package websocket implements the WebSocket protocol defined in RFC 6455.

Jump to

Keyboard shortcuts

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