eudore

package module
v0.0.0-...-3eafb10 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2023 License: MIT Imports: 49 Imported by: 13

README

Eudore

godoc Build Status codecov

eudore是一个golang轻量级web框架核心,可以轻松扩展成一个技术栈专用框架,具有完整框架设计体系。

反馈和交流请加群组:QQ群373278915

Features

  • 易扩展:主要设计目标、核心全部解耦,接口即为逻辑。
  • 简单:对象语义明确,框架代码量少复杂度低,无依赖库。
  • 易用:允许Appcation和Context自由添加功能方法。
  • 高性能:各部分实现与同类库相比性能相似。

安装

eudore基于go version go1.20.1 linux/amd64版本下开发。

go get -v -u github.com/eudore/eudore

文档

Documentation

Overview

Package eudore golang http framework, less is more.

source: https://github.com/eudore/eudore

wiki: https://github.com/eudore/eudore/wiki

exapmle: https://github.com/eudore/eudore/tree/master/_example

godev: https://pkg.go.dev/github.com/eudore/eudore

Index

Constants

View Source
const (
	// EnvEudoreListeners 定义启动fd的地址。
	EnvEudoreDaemonListeners = "EUDORE_DAEMON_LISTENERS"
	// EnvEudoreDaemonRestartID 定义重启时父进程的pid,由子进程kill。
	EnvEudoreDaemonRestartID = "EUDORE_DAEMON_RESTART_ID"
	// EnvEudoreDaemonEnable 用于表示是否fork后台启动,会禁用Logger stdout输出。
	EnvEudoreDaemonEnable = "EUDORE_DAEMON_ENABLE"
	// EnvEudoreDaemonTimeout 定义daemon等待restart和stop命令完成的超时秒数。
	EnvEudoreDaemonTimeout = "EUDORE_DAEMON_TIMEOUT"

	StatusContinue                      = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols            = 101 // RFC 7231, 6.2.2
	StatusProcessing                    = 102 // RFC 2518, 10.1
	StatusOK                            = 200 // RFC 7231, 6.3.1
	StatusCreated                       = 201 // RFC 7231, 6.3.2
	StatusAccepted                      = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo          = 203 // RFC 7231, 6.3.4
	StatusNoContent                     = 204 // RFC 7231, 6.3.5
	StatusResetContent                  = 205 // RFC 7231, 6.3.6
	StatusPartialContent                = 206 // RFC 7233, 4.1
	StatusMultiStatus                   = 207 // RFC 4918, 11.1
	StatusAlreadyReported               = 208 // RFC 5842, 7.1
	StatusIMUsed                        = 226 // RFC 3229, 10.4.1
	StatusMultipleChoices               = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently              = 301 // RFC 7231, 6.4.2
	StatusFound                         = 302 // RFC 7231, 6.4.3
	StatusSeeOther                      = 303 // RFC 7231, 6.4.4
	StatusNotModified                   = 304 // RFC 7232, 4.1
	StatusUseProxy                      = 305 // RFC 7231, 6.4.5
	StatusTemporaryRedirect             = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect             = 308 // RFC 7538, 3
	StatusBadRequest                    = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                  = 401 // RFC 7235, 3.1
	StatusPaymentRequired               = 402 // RFC 7231, 6.5.2
	StatusForbidden                     = 403 // RFC 7231, 6.5.3
	StatusNotFound                      = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed              = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                 = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired             = 407 // RFC 7235, 3.2
	StatusRequestTimeout                = 408 // RFC 7231, 6.5.7
	StatusConflict                      = 409 // RFC 7231, 6.5.8
	StatusGone                          = 410 // RFC 7231, 6.5.9
	StatusLengthRequired                = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed            = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge         = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong             = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType          = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable  = 416 // RFC 7233, 4.4
	StatusExpectationFailed             = 417 // RFC 7231, 6.5.14
	StatusTeapot                        = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest            = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity           = 422 // RFC 4918, 11.2
	StatusLocked                        = 423 // RFC 4918, 11.3
	StatusFailedDependency              = 424 // RFC 4918, 11.4
	StatusTooEarly                      = 425 // RFC 8470, 5.2.
	StatusUpgradeRequired               = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired          = 428 // RFC 6585, 3
	StatusTooManyRequests               = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge   = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons    = 451 // RFC 7725, 3
	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
	StauusClientClosedRequest           = 499 // nginx

	HeaderAccept                          = "Accept"
	HeaderAcceptCharset                   = "Accept-Charset"
	HeaderAcceptEncoding                  = "Accept-Encoding"
	HeaderAcceptLanguage                  = "Accept-Language"
	HeaderAcceptRanges                    = "Accept-Ranges"
	HeaderAcceptPost                      = "Accept-Post"
	HeaderAcceptPatch                     = "Accept-Patch"
	HeaderAccessControlAllowCredentials   = "Access-Control-Allow-Credentials"
	HeaderAccessControlAllowHeaders       = "Access-Control-Allow-Headers"
	HeaderAccessControlAllowMethods       = "Access-Control-Allow-Methods"
	HeaderAccessControlAllowOrigin        = "Access-Control-Allow-Origin"
	HeaderAccessControlExposeHeaders      = "Access-Control-Expose-Headers"
	HeaderAccessControlMaxAge             = "Access-Control-Max-Age"
	HeaderAccessControlRequestHeaders     = "Access-Control-Request-Headers"
	HeaderAccessControlRequestMethod      = "Access-Control-Request-Method"
	HeaderAge                             = "Age"
	HeaderAllow                           = "Allow"
	HeaderAltSvc                          = "Alt-Svc"
	HeaderAuthorization                   = "Authorization"
	HeaderCacheControl                    = "Cache-Control"
	HeaderClearSiteData                   = "Clear-Site-Data"
	HeaderConnection                      = "Connection"
	HeaderContentDisposition              = "Content-Disposition"
	HeaderContentEncoding                 = "Content-Encoding"
	HeaderContentLanguage                 = "Content-Language"
	HeaderContentLength                   = "Content-Length"
	HeaderContentLocation                 = "Content-Location"
	HeaderContentRange                    = "Content-Range"
	HeaderContentSecurityPolicy           = "Content-Security-Policy"
	HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only"
	HeaderContentType                     = "Content-Type"
	HeaderCookie                          = "Cookie"
	HeaderDate                            = "Date"
	HeaderETag                            = "Etag"
	HeaderEarlyData                       = "Early-Data"
	HeaderExpect                          = "Expect"
	HeaderExpectCT                        = "Expect-Ct"
	HeaderExpires                         = "Expires"
	HeaderFeaturePolicy                   = "Feature-Policy"
	HeaderForwarded                       = "Forwarded"
	HeaderFrom                            = "From"
	HeaderHost                            = "Host"
	HeaderIfMatch                         = "If-Match"
	HeaderIfModifiedSince                 = "If-Modified-Since"
	HeaderIfNoneMatch                     = "If-None-Match"
	HeaderIfRange                         = "If-Range"
	HeaderIfUnmodifiedSince               = "If-Unmodified-Since"
	HeaderIndex                           = "Index"
	HeaderKeepAlive                       = "Keep-Alive"
	HeaderLastModified                    = "Last-Modified"
	HeaderLocation                        = "Location"
	HeaderOrigin                          = "Origin"
	HeaderPragma                          = "Pragma"
	HeaderProxyAuthenticate               = "Proxy-Authenticate"
	HeaderProxyAuthorization              = "Proxy-Authorization"
	HeaderProxyConnection                 = "Proxy-Connection"
	HeaderPublicKeyPins                   = "Public-Key-Pins"
	HeaderPublicKeyPinsReportOnly         = "Public-Key-Pins-Report-Only"
	HeaderRange                           = "Range"
	HeaderReferer                         = "Referer"
	HeaderReferrerPolicy                  = "Referrer-Policy"
	HeaderRetryAfter                      = "Retry-After"
	HeaderSecWebSocketAccept              = "Sec-WebSocket-Accept"
	HeaderServer                          = "Server"
	HeaderServerTiming                    = "Server-Timing"
	HeaderSetCookie                       = "Set-Cookie"
	HeaderSourceMap                       = "SourceMap"
	HeaderStrictTransportSecurity         = "Strict-Transport-Security"
	HeaderTE                              = "Te"
	HeaderTimingAllowOrigin               = "Timing-Allow-Origin"
	HeaderTk                              = "Tk"
	HeaderTrailer                         = "Trailer"
	HeaderTransferEncoding                = "Transfer-Encoding"
	HeaderUpgrade                         = "Upgrade"
	HeaderUpgradeInsecureRequests         = "Upgrade-Insecure-Requests"
	HeaderUserAgent                       = "User-Agent"
	HeaderVary                            = "Vary"
	HeaderVia                             = "Via"
	HeaderWWWAuthenticate                 = "Www-Authenticate"
	HeaderWarning                         = "Warning"
	HeaderXContentTypeOptions             = "X-Content-Type-Options"
	HeaderXCSRFToken                      = "X-Csrf-Token"
	HeaderXDNSPrefetchControl             = "X-Dns-Prefetch-Control"
	HeaderXForwardedFor                   = "X-Forwarded-For"
	HeaderXForwardedHost                  = "X-Forwarded-Host"
	HeaderXForwardedProto                 = "X-Forwarded-Proto"
	HeaderXFrameOptions                   = "X-Frame-Options"
	HeaderXXSSProtection                  = "X-Xss-Protection"
	HeaderXRealIP                         = "X-Real-Ip"
	HeaderXRequestID                      = "X-Request-Id"
	HeaderXTraceID                        = "X-Trace-Id"
	HeaderXEudoreAdmin                    = "X-Eudore-Admin"
	HeaderXEudoreCache                    = "X-Eudore-Cache"
	HeaderXEudoreRoute                    = "X-Eudore-Route"

	MethodAny     = "ANY"
	MethodGet     = "GET"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodDelete  = "DELETE"
	MethodHead    = "HEAD"
	MethodPatch   = "PATCH"
	MethodOptions = "OPTIONS"
	MethodConnect = "CONNECT"
	MethodTrace   = "TRACE"

	MimeText                       = "text/*"
	MimeTextPlain                  = "text/plain"
	MimeTextMarkdown               = "text/markdown"
	MimeTextJavascript             = "text/javascript"
	MimeTextHTML                   = "text/html"
	MimeTextCSS                    = "text/css"
	MimeTextXML                    = "text/xml"
	MimeApplicationYAML            = "application/yaml"
	MimeApplicationXML             = "application/xml"
	MimeApplicationProtobuf        = "application/protobuf"
	MimeApplicationJSON            = "application/json"
	MimeApplicationForm            = "application/x-www-form-urlencoded"
	MimeApplicationOctetStream     = "application/octet-stream"
	MimeMultipartForm              = "multipart/form-data"
	MimeMultipartMixed             = "multipart/mixed"
	MimeCharsetUtf8                = "charset=utf-8"
	MimeTextPlainCharsetUtf8       = MimeTextPlain + "; " + MimeCharsetUtf8
	MimeTextMarkdownCharsetUtf8    = MimeTextMarkdown + "; " + MimeCharsetUtf8
	MimeTextJavascriptCharsetUtf8  = MimeTextJavascript + "; " + MimeCharsetUtf8
	MimeTextHTMLCharsetUtf8        = MimeTextHTML + "; " + MimeCharsetUtf8
	MimeTextCSSCharsetUtf8         = MimeTextCSS + "; " + MimeCharsetUtf8
	MimeTextXMLCharsetUtf8         = MimeTextXML + "; " + MimeCharsetUtf8
	MimeApplicationYAMLCharsetUtf8 = MimeApplicationYAML + "; " + MimeCharsetUtf8
	MimeApplicationXMLCharsetUtf8  = MimeApplicationXML + "; " + MimeCharsetUtf8
	MimeApplicationJSONCharsetUtf8 = MimeApplicationJSON + "; " + MimeCharsetUtf8
	MimeApplicationFormCharsetUtf8 = MimeApplicationForm + "; " + MimeCharsetUtf8

	ParamAction          = "action"
	ParamAllow           = "allow"
	ParamAutoIndex       = "autoindex"
	ParamBasicAuth       = "basicauth"
	ParamCaller          = "caller"
	ParamControllerGroup = "controllergroup"
	ParamDepth           = "depth"
	ParamLoggerKind      = "loggerkind"
	ParamPrefix          = "prefix"
	ParamRegister        = "register"
	ParamTemplate        = "template"
	ParamRoute           = "route"
	ParamUserid          = "Userid"
	ParamUsername        = "Username"
	ParamPolicy          = "Policy"
	ParamResource        = "Resource"
)

定义eudore定义各种常量。

Variables

View Source
var (
	// ContextKeyApp 定义获取app的Key。
	ContextKeyApp = NewContextKey("app")
	// ContextKeyAppKeys 定义获取app全部可获取数据keys的Key。
	ContextKeyAppKeys = NewContextKey("app-keys")
	// ContextKeyLogger 定义获取logger的Key。
	ContextKeyLogger = NewContextKey("logger")
	// ContextKeyConfig 定义获取config的Key。
	ContextKeyConfig = NewContextKey("config")
	// ContextKeyDatabase 定义获取database的Key。
	ContextKeyDatabase = NewContextKey("database")
	// ContextKeyClient 定义获取client的Key。
	ContextKeyClient = NewContextKey("client")
	// ContextKeyClientTrace 定义获取client-trace的Key。
	ContextKeyClientTrace = NewContextKey("client-trace")
	// ContextKeyServer 定义获取server的Key。
	ContextKeyServer = NewContextKey("server")
	// ContextKeyRouter 定义获取router的Key。
	ContextKeyRouter = NewContextKey("router")
	// ContextKeyContextPool 定义获取context-pool的Key。
	ContextKeyContextPool = NewContextKey("context-pool")
	// ContextKeyError 定义获取error的Key。
	ContextKeyError = NewContextKey("error")
	// ContextKeyBind 定义获取bind的Key。
	ContextKeyBind = NewContextKey("bind")
	// ContextKeyValidater 定义获取validate的Key。
	ContextKeyValidater = NewContextKey("validater")
	// ContextKeyFilter 定义获取filte的Key。
	ContextKeyFilter = NewContextKey("filter")
	// ContextKeyFilterRules 定义获取filte-data的Key。
	ContextKeyFilterRules = NewContextKey("filter-rules")
	// ContextKeyRender 定义获取render的Key。
	ContextKeyRender = NewContextKey("render")
	// ContextKeyHandlerExtender 定义获取handler-extender的Key。
	ContextKeyHandlerExtender = NewContextKey("handler-extender")
	// ContextKeyFuncCreator 定义获取func-creator的Key。
	ContextKeyFuncCreator = NewContextKey("func-creator")
	// ContextKeyTemplate 定义获取templdate的Key。
	ContextKeyTemplate = NewContextKey("templdate")
	// ContextKeyTrace 定义获取trace的Key。
	ContextKeyTrace = NewContextKey("trace")
	// ContextKeyDaemonCommand 定义获取daemon-command的Key。
	ContextKeyDaemonCommand = NewContextKey("daemon-command")
	// ContextKeyDaemonSignal 定义获取daemon-signal的Key。
	ContextKeyDaemonSignal = NewContextKey("daemon-signal")
	// ContextKeyDatabaseRuntime 定义获取database-runtime的Key。
	ContextKeyDatabaseRuntime = NewContextKey("database-runtime")
	// DefaultClientDialKeepAlive 定义默认DialContext超时时间。
	DefaultClientDialKeepAlive = 30 * time.Second
	// DefaultClientDialTimeout 定义默认DialContext超时时间。
	DefaultClientDialTimeout = 30 * time.Second
	// DefaultClientHost 定义clientStd默认使用的Host。
	DefaultClientHost = "localhost:80"
	// DefaultClientInternalHost 定义clientStd使用内部连接的Host。
	DefaultClientInternalHost = "127.0.0.10:80"
	// DefaultClientParseErrStar 定义NewClientParseErr解析err的状态码范围。
	DefaultClientParseErrStar = 500
	// DefaultClientParseErrEnd 定义NewClientParseErr解析err的状态码范围。
	DefaultClientParseErrEnd = 500
	// DefaultClientTimeout 定义客户端默认超时时间。
	DefaultClientTimeout = 30 * time.Second
	// DefaultClinetHopHeaders 定义Hop to Hop Header。
	DefaultClinetHopHeaders = [...]string{
		HeaderConnection,
		HeaderUpgrade,
		HeaderKeepAlive,
		HeaderProxyConnection,
		HeaderProxyAuthenticate,
		HeaderProxyAuthorization,
		HeaderTE,
		HeaderTrailer,
		HeaderTransferEncoding,
	}
	// DefaultClinetLoggerLevel 定义Client默认最小输出日志级别。
	DefaultClinetLoggerLevel = LoggerError
	// DefaultClinetRetryStatus 定义NewClientRetryNetwork重试状态码。
	DefaultClinetRetryStatus = map[int]bool{
		StatusTooManyRequests:     true,
		StauusClientClosedRequest: true,
		StatusBadGateway:          true,
		StatusServiceUnavailable:  true,
		StatusGatewayTimeout:      true,
	}
	// DefaultConfigAllParseFunc 定义Config默认使用的解析函数。
	DefaultConfigAllParseFunc = []ConfigParseFunc{
		NewConfigParseEnvFile(),
		NewConfigParseDefault(),
		NewConfigParseJSON("config"),
		NewConfigParseArgs(nil),
		NewConfigParseEnvs("ENV_"),
		NewConfigParseWorkdir("workdir"),
		NewConfigParseHelp("help"),
	}
	// DefaultConfigEnvFiles 定义NewConfigParseEnvFile函数默认读取ENV文件。
	DefaultConfigEnvFiles = ".env"
	// DefaultContextMaxHandler 定义请求上下文handler数量上限,需要小于该值。
	DefaultContextMaxHandler = 0xff
	// DefaultContextMaxApplicationFormSize 默认解析ApplicationFrom时body限制长度;
	// 如果Body实现Limit() int64方法忽略该值。
	DefaultContextMaxApplicationFormSize int64 = 10 << 20 // 10M
	// DefaultContextMaxMultipartFormMemory 默认解析MultipartFrom时body使用内存大小。
	DefaultContextMaxMultipartFormMemory int64 = 32 << 20 // 32 MB
	// DefaultContextPushNotSupportedError 定义Context.Push时是否输出http.ErrNotSupported错误。
	DefaultContextPushNotSupportedError = true
	// DefaultFuncCreator 定义全局默认FuncCreator, RouetrCoreStd默认使用。
	DefaultFuncCreator = NewFuncCreator()
	// DefaultHandlerBindFormTags 定义bind form使用tags。
	DefaultHandlerBindFormTags = []string{"form", "alias"}
	// DefaultHandlerBindHeaderTags 定义bind header使用tags。
	DefaultHandlerBindHeaderTags = []string{"header", "alias"}
	// DefaultHandlerBindURLTags 定义bind url使用tags。
	DefaultHandlerBindURLTags = []string{"url", "alias"}
	// DefaultHandlerDataCode 定义Bind/Validate/Filter/Render返回错误时使用的自定义Code。
	DefaultHandlerDataCode = [4]int{}
	// DefaultHandlerDataStatus 定义Bind/Validate/Filter/Render返回错误时使用的自定义Status。
	DefaultHandlerDataStatus = [4]int{}
	// DefaultHandlerRenderFunc 定义默认使用的Render函数。
	DefaultHandlerRenderFunc = RenderJSON
	// DefaultHandlerValidateTag 定义NewValidateField获取校验规则的结构体tag。
	DefaultHandlerValidateTag = "validate"
	// DefaultHandlerEmbedCacheControl 定义默认NewHandlerEmbedFunc使用的Cache-Control缓存策略。
	DefaultHandlerEmbedCacheControl = "no-cache"
	// DefaultHandlerEmbedTime 设置http返回embed文件的最后修改时间,默认为服务启动时间。
	// 如果服务存在多副本部署,通过设置相同的值使多副本间的时间版本一致,保证启用304缓存。
	DefaultHandlerEmbedTime = time.Now()
	// DefaultHandlerExtender 为默认的函数扩展处理者。
	DefaultHandlerExtender = NewHandlerExtender()
	// DefaultHandlerExtenderAllowType 定义handlerExtenderBase允许使用的参数类型。
	DefaultHandlerExtenderAllowType = map[reflect.Kind]struct{}{
		reflect.Func: {}, reflect.Interface: {},
		reflect.Map: {}, reflect.Ptr: {}, reflect.Slice: {}, reflect.Struct: {},
	}
	// DefaultHandlerExtenderFuncs 定义NewHandlerExtender默认注册的扩展函数。
	DefaultHandlerExtenderFuncs = []any{
		NewHandlerEmbed,
		NewHandlerFunc,
		NewHandlerFuncContextError,
		NewHandlerFuncContextAnyError,
		NewHandlerFuncContextRender,
		NewHandlerFuncContextRenderError,
		NewHandlerFuncError,
		NewHandlerFuncRPC,
		NewHandlerFuncRPCMap,
		NewHandlerFuncRender,
		NewHandlerFuncRenderError,
		NewHandlerFuncString,
		NewHandlerHTTP,
		NewHandlerHTTPFileSystem,
		NewHandlerHTTPFunc1,
		NewHandlerHTTPFunc2,
		NewHandlerHTTPHandler,
		NewHandlerStringer,
	}
	// DefaultLoggerDepthMaxStack 定义GetCallerStacks函数默认显示栈最大层数。
	DefaultLoggerDepthMaxStack = 0x4f
	// DefaultLoggerNull 定义空日志输出器。
	DefaultLoggerNull            = NewLoggerNull()
	DefaultLoggerEnableHookFatal = false
	DefaultLoggerEnableHookMeta  = false
	DefaultLoggerEnableStdColor  = true
	// DefaultLoggerEntryBufferLength 定义默认LoggerEntry缓冲长度。
	DefaultLoggerEntryBufferLength = 2048
	// DefaultLoggerEntryFieldsLength 定义默认LoggerEntry Field数量。
	DefaultLoggerEntryFieldsLength = 4
	// DefaultLoggerFormatter 定义Logger默认日志格式化格式。
	DefaultLoggerFormatter = "json"
	// DefaultLoggerFormatterFormatTime 定义默认日志输出和contextBase.WriteError的时间格式。
	DefaultLoggerFormatterFormatTime = "2006-01-02 15:04:05.000"
	// DefaultLoggerFormatterKeyLevel 定义默认Level字段输出名称。
	DefaultLoggerFormatterKeyLevel = "level"
	// DefaultLoggerFormatterKeyMessage 定义默认Message字段输出名称。
	DefaultLoggerFormatterKeyMessage = "message"
	// DefaultLoggerFormatterKeyTime 定义默认Time字段输出名称。
	DefaultLoggerFormatterKeyTime = "time"
	// DefaultLoggerLevelStrings 定义日志级别输出字符串。
	DefaultLoggerLevelStrings = [...]string{"DEBUG", "INFO", "WARNING", "ERROR", "FATAL", "DISCARD"}
	// DefaultLoggerWriterRotateDataKeys 定义日期滚动时/天/月/年的关键字,顺序不可变化。
	DefaultLoggerWriterRotateDataKeys = [...]string{"hh", "dd", "mm", "yyyy"}
	// DefaultLoggerWriterStdoutWindowsColor 定义GOOS=windows时是否使用彩色level字段。
	DefaultLoggerWriterStdoutWindowsColor = false
	// DefaultRouterAllMethod 定义路由器允许注册的全部方法,前六种方法在RouterCore始终存在。
	DefaultRouterAllMethod = []string{
		MethodGet, MethodPost, MethodPut,
		MethodDelete, MethodHead, MethodPatch,
		MethodOptions, MethodConnect, MethodTrace,
	}
	// DefaultRouterAnyMethod 定义Any方法的注册使用的方法。
	DefaultRouterAnyMethod = append([]string{}, DefaultRouterAllMethod[0:6]...)
	// DefaultRouterCoreMethod 定义routerCoreStd实现中默认存储的6种方法处理对象。
	DefaultRouterCoreMethod = append([]string{}, DefaultRouterAllMethod[0:6]...)
	// DefaultRouterLoggerKind 定义默认RouterStd输出那些类型日志。
	DefaultRouterLoggerKind = "all"
	// DefaultServerListen 定义ServerListenConfig使用Listen函数,用于hook listen。
	DefaultServerListen            = net.Listen
	DefaultServerReadTimeout       = 60 * time.Second
	DefaultServerReadHeaderTimeout = 60 * time.Second
	DefaultServerWriteTimeout      = 60 * time.Second
	DefaultServerIdleTimeout       = 60 * time.Second
	// DefaultServerShutdownWait 定义Server优雅退出等待时间。
	DefaultServerShutdownWait = 30 * time.Second
	// DefaultTemplateNameStaticIndex 定义默认渲染静态目录模板名称。
	DefaultTemplateNameStaticIndex = "eudore-embed-index"
	// DefaultTemplateNameRenderData 定义默认RenderHTML模板名称。
	DefaultTemplateNameRenderData = "eudore-render-data"
	// DefaultTemplateContentStaticIndex 定义默认渲染静态目录模板内容。
	DefaultTemplateContentStaticIndex = templateEmbedIndex
	// DefaultTemplateContentRenderData 定义默认RenderHTML模板内容。
	DefaultTemplateContentRenderData = tempdateRenderData
	// DefaultTemplateInit 定义App默认加载模板内容。
	DefaultTemplateInit = fmt.Sprintf(`{{- define "%s" -}}%s{{- end -}}{{- define "%s" -}}%s{{- end -}}`,
		DefaultTemplateNameStaticIndex, DefaultTemplateContentStaticIndex,
		DefaultTemplateNameRenderData, DefaultTemplateContentRenderData,
	)
	// DefaultValueGetSetTags 定义Get/SetAny默认的tag。
	DefaultValueGetSetTags = []string{"alias"}
	// DefaultValueParseTimeFormats 定义尝试解析的时间格式。
	DefaultValueParseTimeFormats = []string{
		"2006-01-02",
		"20060102",
		"15:04:05",
		"2006-01-02 15:04:05",
		"2006-01-02T15:04:05Z07:00",
		"2006-01-02T15:04:05.999999999Z07:00",
		time.ANSIC,
		time.UnixDate,
		time.RubyDate,
		time.RFC822,
		time.RFC822Z,
		time.RFC850,
		time.RFC1123,
		time.RFC1123Z,
		time.RFC3339,
		time.RFC3339Nano,
	}
	// DefaultValueParseTimeFixed 定义预定义时间格式长度是否固定,避免解析长度不相同的时间格式。
	DefaultValueParseTimeFixed = []bool{
		true, true, true, true, true, true,
		false, false, true, true, true, true, true, true, true, true,
	}
	// DefaultDaemonPidfile 定义daemon默认使用的pid文件。
	DefaultDaemonPidfile = "/var/run/eudore.pid"
	// DefaultGodocServer 定义应用默认使用的godoc服务器域名。
	DefaultGodocServer = "https://golang.org"
	// DefaultTraceServer 定义应用默认使用的jaeger链路追踪服务器域名。
	DefaultTraceServer = ""

	// ErrClientBodyFormNotGetBody 定义ClientBodyForm无法获取复制对象错误。
	ErrClientBodyFormNotGetBody = errors.New("client bodyForm contains files that cannot be copied, cannot copy body")
	// ErrFuncCreatorNotFunc 定义FuncCreator无法获取或创建函数。
	ErrFuncCreatorNotFunc = errors.New("not found or create func")
	// ErrHandlerExtenderParamNotFunc 定义调用RegisterHandlerExtender函数时,参数必须是一个函数。
	ErrHandlerExtenderParamNotFunc = errors.New("the parameter type of RegisterNewHandler must be a function")
	// ErrLoggerLevelUnmarshalText 日志级别解码错误,请检查输出的[]byte是否有效。
	ErrLoggerLevelUnmarshalText = errors.New("logger level UnmarshalText error")
	// ErrRenderHandlerSkip 定义Renders执行Render时无法渲染,跳过当前Render。
	ErrRenderHandlerSkip = errors.New("render hander skip")
	// ErrResponseWriterNotHijacker ResponseWriterHTTP对象没有实现http.Hijacker接口。
	ErrResponseWriterNotHijacker = errors.New("http.Hijacker interface is not supported")
	// ErrValueInputDataNil 在Converter方法时,输出参数是空。
	ErrValueInputDataNil = errors.New("converter input value is nil")
	// ErrValueInputDataNotPtr 在Converter方法时,输出参数是空。
	ErrValueInputDataNotPtr = errors.New("converter input value not is ptr")

	// ErrFormatBindDefaultNotSupportContentType BindDefault函数不支持当前的Content-Type Header。
	ErrFormatBindDefaultNotSupportContentType = "BindDefault: not support content type header: %s"
	// ErrFormatClintCheckStatusError 定义Client检查status不匹配错误。
	ErrFormatClintCheckStatusError = "clint check status is %d not in %v"
	// ErrFormatClintParseBodyError 定义Client解析Body时无法解析Content-Type错误。
	ErrFormatClintParseBodyError = "eudore client parse not suppert Content-Type: %s"
	// ErrFormatContextParseFormNotSupportContentType Context解析Form时时,不支持Content-Type。
	ErrFormatContextParseFormNotSupportContentType = "eudore.Context: parse form not supported Content-Type: %s"
	// ErrFormatContextRedirectInvalid Context.Redirect方法使用了无效的状态码。
	ErrFormatContextRedirectInvalid = "eudore.Context: invalid redirect status code %d"
	// ErrFormatContextPushFailed Context.Push方法推送资源错误。
	ErrFormatContextPushFailed = "eudore.Context: push resource %s failed: %w"
	// ErrFormatFuncCreatorRegisterInvalidType fc注册函数类似是无效的。
	ErrFormatFuncCreatorRegisterInvalidType = "Register func '%s' type is %T, must 'func(T) bool' or 'func(string) (func(T) bool, error)'"
	// ErrFormatHandlerExtenderInputParamError RegisterHandlerExtender函数注册的函数参数错误。
	ErrFormatHandlerExtenderInputParamError = "the '%s' input parameter is illegal and should be one func/interface/ptr/struct"
	// ErrFormatHandlerExtenderOutputParamError RegisterHandlerExtender函数注册的函数返回值错误。
	ErrFormatHandlerExtenderOutputParamError = "the '%s' output parameter is illegal and should be a HandlerFunc object"
	// ErrFormatRouterStdAddController RouterStd控制器路由注入错误。
	ErrFormatRouterStdAddController = "the RouterStd.AddController Inject %s error: %w"
	// ErrFormatRouterStdAddHandlerExtender RouterStd添加扩展处理函数错误。
	ErrFormatRouterStdAddHandlerExtender = "the RouterStd.AddHandlerExtender path is '%s' RegisterHandlerExtender error: %w"
	// ErrFormatRouterStdaddHandlerMethodInvalid RouterStd.addHandler 的添加的是无效的,全部有效方法为RouterAnyMethod。
	ErrFormatRouterStdAddHandlerMethodInvalid = "the RouterStd.addHandler arg method '%s' is invalid, add fullpath: '%s'"
	// ErrFormatRouterStdaddHandlerRecover RouterStd注册路由时恢复panic。
	ErrFormatRouterStdAddHandlerRecover = "the RouterStd.addHandler arg method is '%s' and path is '%s', recover error: %w"
	// ErrFormarRouterStdLoadInvalidFunc RouterStd无法加载路径对应的校验函数。
	ErrFormarRouterStdLoadInvalidFunc = "loadCheckFunc path is invalid, load path '%s' error: %v "
	// ErrFormatRouterStdNewHandlerFuncsUnregisterType RouterStd添加处理对象或中间件的第n个参数类型未注册,需要先使用RegisterHandlerExtender或AddHandlerExtender注册该函数类型。
	ErrFormatRouterStdNewHandlerFuncsUnregisterType = "the RouterStd.newHandlerFuncs path is '%s', %dth handler parameter type is '%s', this is the unregistered handler type"
	// ErrFormatProtobufDecodeNilInteface 定义protobuf解码到空接口。
	ErrFormatProtobufDecodeNilInteface    = "protobuf decode %s interface %s is nil"
	ErrFormatProtobufDecodeInvalidFlag    = "protobuf decode %s invalid flag %d"
	ErrFormatProtobufDecodeInvalidKind    = "protobuf decode %s invalid kind %s"
	ErrFormatProtobufDecodeReadError      = "protobuf decode %s read %s error: %w"
	ErrFormatProtobufDecodeReadInvalid    = "protobuf decode %s read length %d invalid has data %d"
	ErrFormatProtobufDecodeMessageNotRead = "protobuf decode message has %d not read"
	ErrFormatProtobufTypeMustSturct       = "protobuf encdoe/decode kind must struct, current type %s"
	// ErrFormatParseValidateFieldError 定义Validate校验失败时输出Error格式。
	ErrFormatValidateErrorFormat = "validate %s.%s field %s check %s rule fatal, value: %%#v"
	// ErrFormatValidateParseFieldError Validate解析结构体规则错误。
	ErrFormatValidateParseFieldError = "validateField %s.%s parse field %s create rule %s error: %s"
	// ErrFormatValueError 定义Value操作错误。
	ErrFormatValueError = "value %s path '%s' error: %w"
	// ErrFormatValueTypeNil 定义Value对象为空。
	ErrFormatValueTypeNil           = "is nil"
	ErrFormatValueAnonymousField    = " is anonymous field"
	ErrFormatValueNotField          = "not found field '%s'"
	ErrFormatValueArrayIndexInvalid = "parse index '%s' is invalid, length is %d"
	ErrFormatValueMapIndexInvalid   = "parse index '%s' is invalid"
	ErrFormatValueMapValueInvalid   = "obtained index '%s' value is invalid"
	ErrFormatValueStructUnexported  = "field '%s' is unexported"
	ErrFormatValueStructNotCanset   = "field '%s' is not canset "
	// ErrFormatConverterSetStringUnknownType setWithString函数遇到未定义的反射类型。
	ErrFormatValueSetStringUnknownType = "setWithString unknown type %s"
	// ErrFormatConverterSetWithValue setWithValue函数中类型无法赋值。
	ErrFormatValueSetWithValue = "the setWithValue method type %s cannot be assigned to type %s"
)

Functions

func BindForm

func BindForm(ctx Context, i any) error

The BindForm function uses form to parse and bind the body.

BindForm 函数使用form解析绑定body。

func BindHeader

func BindHeader(ctx Context, i any) error

The BindHeader function implements binding using header data.

The header name prefix must be 'X-', example: X-Euduore-Name => Eudore.Name.

BindHeader 函数实现使用header数据bind。

header名称前缀必须是'X-',example: X-Euduore-Name => Eudore.Name。

func BindJSON

func BindJSON(ctx Context, i any) error

The BindJSON function uses encoding/json to parse and bind the body.

BindJSON 函数使用encoding/json解析绑定body。

func BindProtobuf

func BindProtobuf(ctx Context, i any) error

The BindProtobuf function uses the built-in protobu to parse the bound body.

BindProtobuf 函数使用内置protobu解析绑定body。

func BindURL

func BindURL(ctx Context, i any) error

The BindURL function uses the url parameter to parse the binding body.

BindURL 函数使用url参数解析绑定body。

func BindXML

func BindXML(ctx Context, i any) error

The BindXML function uses encoding/xml to parse the bound body.

BindXML 函数使用encoding/xml解析绑定body。

func ControllerInjectAutoRoute

func ControllerInjectAutoRoute(controller Controller, router Router) error

ControllerInjectAutoRoute function generates routing rules based on the controller rules, and the usage method is converted into a processing function to support routers.

Routing group: If the'ControllerGroup(string) string' method is implemented, the routing group is returned; if the routing parameter ParamControllerGroup is included, it is used; otherwise, the controller name is used to turn the path.

Routing path: Convert the method with the request method as the prefix to the routing method and path, and then use the map[method]path returned by the'ControllerRoute() map[string]string' method to overwrite the routing path.

Method conversion rules: The method prefix must be a valid request method (within DefaultRouterAllMethod), the remaining path is converted to a path, ByName is converted to variable matching/:name, and the last By of the method path is converted to /*; The return path of ControllerRoute is'-' and the method is ignored. The first character is”, which means it is a path append parameter.

Routing parameters: If you implement the'ControllerParam(string, string, string) string' method to return routing parameters, otherwise use "controllername=%s.%s controllermethod=%s".

Controller combination: If the controller combines other objects, only the methods of the object whose name suffix is Controller are reserved, and other methods with embedded properties will be ignored.

ControllerInjectAutoRoute 函数基于控制器规则生成路由规则,使用方法转换成处理函数支持路由器。

路由组: 如果实现'ControllerGroup(string) string'方法返回路由组; 如果包含路由参数ParamControllerGroup则使用;否则使用控制器名称驼峰转路径。

路由路径: 将请求方法为前缀的方法转换成路由方法和路径, 然后使用'ControllerRoute() map[string]string'方法返回的map[method]path覆盖路由路径。

方法转换规则: 方法前缀必须是有效的请求方法(DefaultRouterAllMethod之内), 剩余路径驼峰转路径,ByName转换成变量匹配/:name,方法路径最后一个By转换成/*; ControllerRoute返回路径为'-'则忽略方法,第一个字符为' '表示为路径追加参数。

路由参数: 如果实现'ControllerParam(string, string, string) string'方法返回路由参数, 否则使用"controllername=%s.%s controllermethod=%s"。

控制器组合: 如果控制器组合了其他对象,仅保留名称后缀为Controller的对象的方法,其他嵌入属性的方法将被忽略。

func GetAny

func GetAny[T string | bool | TypeNumber](s any, defaults ...T) T

GetAny 函数类型Value转换成另外一个类型。

func GetAnyByPath

func GetAnyByPath(i any, key string) any

GetAnyByPath method A more path to get an attribute from an object.

The path will be split using '.' and then look for the path in turn.

Structure attributes can use the structure tag 'alias' to match attributes.

Returns a null value if the match fails.

根据路径来从一个对象获得一个属性。

路径将使用'.'分割,然后依次寻找路径。

结构体属性可以使用结构体标签'alias'来匹配属性。

如果匹配失败直接返回空值。

func GetAnyByPathWithTag

func GetAnyByPathWithTag(i any, key string, tags []string, all bool) (any, error)

GetAnyByPathWithTag 函数和GetAnyByPath函数相同,可以额外设置tags,同时会返回error。

func GetAnyByPathWithValue

func GetAnyByPathWithValue(i any, key string, tags []string, all bool) (reflect.Value, error)

GetAnyByPathWithValue 函数和Get函数相同,可以允许查找私有属性并返回reflect.Value。

func GetAnyByString

func GetAnyByString[T string | bool | TypeNumber | time.Time | time.Duration](str string, defaults ...T) T

GetAnyByString 函数将字符串转换为其他值。

func GetAnyByStringWithError

func GetAnyByStringWithError[T string | bool | TypeNumber | time.Time | time.Duration](str string, defaults ...T) (T, error)

GetAnyByStringWithError 函数将字符串转换成泛型数值。

func GetAnyDefault

func GetAnyDefault[T comparable](arg1, arg2 T) T

GetAnyDefault 函数返回非空值。

func GetAnyDefaults

func GetAnyDefaults[T comparable](args ...T) T

GetAnyDefaults 函数返回第一个非空值。

func GetCallerFuncFile

func GetCallerFuncFile(depth int) (string, string)

GetCallerFuncFile 函数获得调用的文件位置和函数名称。

文件位置会从第一个src后开始截取,处理gopath下文件位置。

func GetCallerStacks

func GetCallerStacks(depth int) []string

GetCallerStacks 函数返回caller栈信息。

func GetStringByAny

func GetStringByAny(i any, strs ...string) string

GetStringByAny 函数将any转换成string

func GetStringRandom

func GetStringRandom(length int) string

GetStringRandom 函数返回指定长度随机字符串。

func HandlerEmpty

func HandlerEmpty(Context)

HandlerFuncs is a collection of HandlerFunc, representing multiple request processing functions.

HandlerEmpty 函数定义一个空的请求上下文处理函数。

func HandlerMetadata

func HandlerMetadata(ctx Context)

HandlerMetadata 函数返回从contextKey获取metadata,可以使用路由参数*或name指定key。

func HandlerRouter403

func HandlerRouter403(ctx Context)

HandlerRouter403 function defines the default 403 processing.

HandlerRouter403 函数定义默认403处理。

func HandlerRouter404

func HandlerRouter404(ctx Context)

HandlerRouter404 function defines the default 404 processing.

HandlerRouter404 函数定义默认404处理。

func HandlerRouter405

func HandlerRouter405(ctx Context)

HandlerRouter405 function defines the default 405 processing and returns Allow and X-Match-Route Header.

HandlerRouter405 函数定义默认405处理,返回Allow和X-Match-Route Header。

func NewClienProxyWriter

func NewClienProxyWriter(writer io.Writer) func(*http.Response) error

NewClienProxyWriter 函数将客户端响应写入另外Writer,

如果Writer实现http.ResponseWriter接口会写入状态码和Header。

func NewClientCheckBody

func NewClientCheckBody(str string) func(*http.Response) error

NewClientCheckBody 方法创建响应选项检查响应body是否包含指定字符串。

func NewClientCheckStatus

func NewClientCheckStatus(status ...int) func(*http.Response) error

NewClientCheckStatus 方法创建响应选项检查响应状态码。

func NewClientOptionHost

func NewClientOptionHost(host string) func(*http.Request)

NewClientOptionHost 函数设置请求Host。

func NewClientParse

func NewClientParse(data any) func(*http.Response) error

NewClientParse 方法创建响应选项解析body数据。

func NewClientParseErr

func NewClientParseErr() func(*http.Response) error

NewClientParseErr 方法创建响应选项,在默认范围时解析body中的Error字段返回。

func NewClientParseIf

func NewClientParseIf(status int, data any) func(*http.Response) error

NewClientParseIf 方法创建响应选项,在指定状态码时解析body数据。

func NewClientParseIn

func NewClientParseIn(star, end int, data any) func(*http.Response) error

NewClientParseIn 方法创建响应选项,在指定状态码范围时解析body数据。

func NewClientTraceWithContext

func NewClientTraceWithContext(ctx context.Context, trace *ClientTrace) context.Context

NewClientTraceWithContext 函数将ClientTrace初始化并绑定到context.Context。

func NewContextBaseFunc

func NewContextBaseFunc(ctx context.Context) func() Context

NewContextBaseFunc 函数使用context.Context创建Context构造函数,用于获取自定义Context。

func NewContextBasePool

func NewContextBasePool(ctx context.Context) *sync.Pool

NewContextBasePool 函数从上下文创建一个Context sync.Pool。

需要从上下文加载ContextKeyApp实现Logger Database Client接口。

ContextBase相关方法文档点击NewContextBase函数跳转到源码查看。

func NewContextKey

func NewContextKey(key string) any

NewContextKey 定义context key。

func NewContextMessgae

func NewContextMessgae(ctx Context, err error, message any) any

NewContextMessgae 方法从请求上下文创建一个error或对象响应对象,记录请求上下文相关信息。

func NewErrorWithCode

func NewErrorWithCode(err error, code int) error

NewErrorWithCode 方法封装error实现Code方法。

func NewErrorWithStatus

func NewErrorWithStatus(err error, status int) error

NewErrorWithStatus 方法封装error实现Status方法。

func NewErrorWithStatusCode

func NewErrorWithStatusCode(err error, status, code int) error

NewErrorWithStatusCode 方法组合ErrorStatus和ErrorCode。

func NewFileSystems

func NewFileSystems(dirs ...any) http.FileSystem

The NewFileSystems function creates a hybrid http.FileSystem object that returns the first file from multiple http.FileSystems.

If the type is string and the path exists, it will be converted to http.Dir; If the type is embed.FS converted to http.FS; If the type is http.FileSystem, add it directly.

NewFileSystems 函数创建一个混合http.FileSystem对象,从多个http.FileSystem返回首个文件。

如果类型为string且路径存在将转换成http.Dir; 如果类型为embed.FS转换成http.FS; 如果类型为http.FileSystem直接追加。

func RenderHTML

func RenderHTML(ctx Context, data any) error

The RenderHTML function creates a template Renderer using a template.

Load *template.Template from ctx.Value(eudore.ContextKeyTemplate), Load the template function from ctx.GetParam("template").

RenderHTML 函数使用模板创建一个模板Renderer。

从ctx.Value(eudore.ContextKeyTemplate)加载*template.Template, 从ctx.GetParam("template")加载模板函数。

func RenderJSON

func RenderJSON(ctx Context, data any) error

The RenderJSON function uses the encoding/json library to implement json deserialization.

If the request Accept is not "application/json", output in json indent format.

RenderJSON 函数使用encoding/json库实现json反序列化。

如果请求Accept不为"application/json",使用json indent格式输出。

func RenderProtobuf

func RenderProtobuf(ctx Context, i any) error

RenderProtobuf function Render Protobuf, using the built-in protobuf encoding, invalid properties will be ignored.

RenderProtobuf 函数Render Protobuf,使用内置protobuf编码,无效属性将忽略。

func RenderText

func RenderText(ctx Context, data any) error

RenderText function Render Text, written using the fmt.Fprint function.

RenderText 函数Render Text,使用fmt.Fprint函数写入。

func RenderXML

func RenderXML(ctx Context, data any) error

RenderXML function Render Xml, using the encoding/xml library to realize xml deserialization.

RenderXML 函数Render Xml,使用encoding/xml库实现xml反序列化。

func SetAnyByPath

func SetAnyByPath(i any, key string, val any) error

The SetAnyByPath function sets the properties of an object, and the object must be a pointer type.

The path will be separated using '.', and then the path will be searched for in sequence.

When the object type selected in the path is ptr, it will be checked to see if it is empty. If the object is empty, it will be initialized by default.

When the object type selected in the path is any, if the object is empty, it will be initialized to map[string]any, otherwise the next operation will be determined based on the value type.

When the object type selected in the path is array, the path will be converted into an object index to set the array elements, and if the index is [], the elements will be appended.

When the object type selected in the path is struct, the attribute name and attribute label 'alias' will be used to match when selecting attributes.

If the value type is a string, it will be converted according to the set target type.

If the target type is a string, the value will be output as a string and then assigned.

SetAnyByPath 函数设置一个对象的属性,改对象必须是指针类型。

路径将使用'.'分割,然后依次寻找路径。

当路径中选择对象类型为ptr时,会检查是否为空,对象为空会默认进行初始化。

当路径中选择对象类型为any时,如果对象为空会初始化为map[string]any, 否则按值类型来判断下一步操作。

当路径中选择对象类型为array时,路径会转换成对象索引来设置数组元素,索引为[]则追加元素。

当路径中选择对象类型为struct时,选择属性时会使用属性名称和属性标签'alias'来匹配。

如果值的类型是字符串,会根据设置的目标类型来转换。

如果目标类型是字符串,将会值输出成字符串然后赋值。

func SetAnyByPathWithTag

func SetAnyByPathWithTag(i any, key string, val any, tags []string, all bool) error

SetAnyByPathWithTag 函数和SetAnyByPath函数相同,可以额外设置tags。

func SetAnyDefault

func SetAnyDefault[T any](arg1, arg2 *T)

func SetHandlerAliasName

func SetHandlerAliasName(i any, name string)

SetHandlerAliasName 函数设置一个函数处理对象原始名称,如果扩展未生成名称,使用此值。

在handlerExtendBase对象和ControllerInjectSingleton函数中使用到,用于传递控制器函数名称。

func SetHandlerFuncName

func SetHandlerFuncName(i HandlerFunc, name string)

SetHandlerFuncName function sets the name of a request context handler.

Note: functions are not comparable, the method names of objects are overwritten by other method names.

SetHandlerFuncName 函数设置一个请求上下文处理函数的名称。

注意:函数不具有可比性,对象的方法的名称会被其他方法名称覆盖。

Types

type App

type App struct {
	context.Context    `alias:"context"`
	context.CancelFunc `alias:"cancelfunc"`
	Logger             `alias:"logger"`
	Config             `alias:"config"`
	Database           `alias:"database"`
	Client             `alias:"client"`
	Server             `alias:"server"`
	Router             `alias:"router"`
	GetWarp            `alias:"getwarp"`
	HandlerFuncs       HandlerFuncs `alias:"handlerfuncs"`
	ContextPool        *sync.Pool   `alias:"contextpool"`
	CancelError        error        `alias:"cancelerror"`

	Values []any `alias:"values"`
	// contains filtered or unexported fields
}

The App struct is defined as the main object for the application, which combines various functional interfaces and implements basic methods. It provides additional features such as

Manage Object Lifecycle
Store global data
Register global middleware
Start port monitoring
Block running service
Get configuration value and convert type

func NewApp

func NewApp() *App

The NewApp() function creates an App object, initializes various components of the application, and returns the App object.

func (*App) AddMiddleware

func (app *App) AddMiddleware(hs ...any) error

AddMiddleware If the first parameter of the AddMiddleware method is the string "global", it will be added to the App as a global request middleware, using NewHandlerExtenderWithContext to create a request processing function, otherwise it is equivalent to calling the app.Rputer.AddMiddleware method.

AddMiddleware 方法如果第一个参数为字符串"global", 为全局请求中间件添加给App(使用NewHandlerExtenderWithContext创建请求处理函数), 否则等同于调用app.Rputer.AddMiddleware方法。

func (*App) Err

func (app *App) Err() error

Err method returns an error at the end of the App Context.

Err 方法返回App Context结束时错误。

func (*App) Listen

func (app *App) Listen(addr string) error

Listen method listens to an http port.

Listen 方法监听一个http端口。

func (*App) ListenTLS

func (app *App) ListenTLS(addr, key, cert string) error

ListenTLS method listens to an https port, if h2 is enabled by default.

ListenTLS 方法监听一个https端口,如果默认开启h2。

func (*App) Parse

func (app *App) Parse() error

func (*App) Run

func (app *App) Run() error

The Run() method starts the application and blocks it until it is finished.

Run 方法启动App阻塞等待App结束。

func (*App) Serve

func (app *App) Serve(ln net.Listener)

Serve method starts a Server monitor non-blocking, and uses the app to process the monitor and return an error.

Serve 方法非阻塞启动一个Server监听,并使用app处理监听结束返回错误。

func (*App) ServeHTTP

func (app *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

The ServeHTTP method implements the http.Handler interface to process http requests.

Create and initialize a Context, set app.HandlerFuncs as the global request handler function of Context. When app.HandlerFuncs is last processed, the app.serveContext method is called, Use app.Router to match the route processing function of this request for secondary request processing.

ServeHTTP 方法实现http.Handler接口,处理http请求。

创建并初始化一个Context,设置app.HandlerFuncs为Context的全局请求处理函数。 在app.HandlerFuncs最后一次处理时,调用了app.serveContext方法, 使用app.Router匹配出这个请求的路由处理函数进行二次请求处理。

func (*App) SetValue

func (app *App) SetValue(key, val any)

SetValue method sets the specified key value from the App. If the value implements the Mount/Unmount method, this method is automatically called when setting and unsetting.

SetValue 方法从App设置指定键值,如果值实现Mount/Unmount方法在设置和取消设置时自动调用该方法。

func (*App) Value

func (app *App) Value(key any) any

Value method gets the specified key value from the App.

Value 方法从App获取指定键值。

type Client

type Client interface {
	NewRequest(context.Context, string, string, ...any) error
	WithClient(...any) Client
	GetClient() *http.Client
}

Client 定义http客户端接口,构建并发送http请求。

func NewClient

func NewClient(options ...any) Client

NewClient 函数创建默认http客户端实现,参数为默认选项。

type ClientBody

type ClientBody interface {
	io.ReadCloser
	GetContentType() string
	GetBody() (io.ReadCloser, error)
	AddValue(string, any)
	AddFile(string, string, any)
}

ClientBody defines the client Body.

The GetBody method returns a shallow copy of the data for request redirection and retry.

The AddValue method sets the data saved by the body.

The AddFile method can add file upload when using MultipartForm.

ClientBody 定义客户端Body。

GetBody方法返回数据浅复制用于请求重定向和重试。

AddValue方法设置body保存的数据。

AddFile方法在MultipartForm时可以添加文件上传。

func NewClientBodyDecoder

func NewClientBodyDecoder(contenttype string, data any, encoder func(io.Writer, any)) ClientBody

The NewClientBodyDecoder function creates a ClientBody encoder, which needs to specify contenttype and encoder.

NewClientBodyDecoder 函数创建一个ClientBody编码器,需要指定contenttype和encoder。

func NewClientBodyForm

func NewClientBodyForm(data url.Values) ClientBody

NewClientBodyForm 函数创建ApplicationForm或MultipartForm请求body。

AddFile方法允许data类型为[]byte io.Reader;如果类型为string则加载这个本地文件。

如果使用AddFile方法添加文件ContentType为MultipartForm。

func NewClientBodyJSON

func NewClientBodyJSON(data any) ClientBody

NewClientBodyJSON 函数创建一个json编码器。

func NewClientBodyProtobuf

func NewClientBodyProtobuf(data any) ClientBody

NewClientBodyProtobuf 函数创建一个protobuf编码器。

func NewClientBodyXML

func NewClientBodyXML(data any) ClientBody

NewClientBodyXML 函数创建一个xml编码器。

type ClientOption

type ClientOption struct {
	Context       context.Context
	Timeout       time.Duration
	Body          io.Reader
	ClientBody    ClientBody
	Values        url.Values
	Header        http.Header
	Headers       []string
	Cookies       []string
	RequestHooks  []func(*http.Request)
	ResponseHooks []func(*http.Response) error
	Retrys        []ClientRetry
	// Trace saves ClientTrace data, and enables httptrace when it is not empty.
	// Trace 保存ClientTrace数据,非空时启用httptrace。
	Trace *ClientTrace
}

ClientOption 定义创建客户端请求时额外选项。

func NewClientOption

func NewClientOption(ctx context.Context, options []any) *ClientOption

NewClientOption 函数使用options创建ClientOption。

func NewClientOptionBasicauth

func NewClientOptionBasicauth(username, password string) *ClientOption

NewClientOptionBasicauth 函数设置请求Basic Auth权限。

func NewClientOptionBearer

func NewClientOptionBearer(bearer string) *ClientOption

NewClientOptionBearer 函数设置请求Bearer认证。

func NewClientOptionHeader

func NewClientOptionHeader(key, val string) *ClientOption

NewClientOptionHeader 函数设置请求Header。

func NewClientOptionUserAgent

func NewClientOptionUserAgent(ua string) *ClientOption

NewClientOptionUserAgent 函数设置请求UA。

type ClientRetry

type ClientRetry struct {
	Max       int
	Condition func(int, *http.Response, error) bool
}

ClientRetry 定义客户端请求重试行为。

func NewClientRetryDigest

func NewClientRetryDigest(username, password string) ClientRetry

NewClientRetryDigest 函数创建一个摘要认证配置,在401时重新发起请求。

func NewClientRetryNetwork

func NewClientRetryNetwork(max int) ClientRetry

NewClientRetryNetwork 函数创建一个网络重试配置。

在err不为空或DefaultClinetRetryStatus指定状态码时,重试请求。

type ClientTrace

type ClientTrace struct {
	sync.Mutex            `alias:"mutex" json:"-" xml:"-" yaml:"-"`
	HTTPStart             time.Time            `alias:"http-start" json:"http-start" xml:"http-start" yaml:"http-start"`
	HTTPDone              time.Time            `alias:"http-done" json:"http-done" xml:"http-done" yaml:"http-done"`
	HTTPDuration          time.Duration        `alias:"http-duration" json:"http-duration" xml:"http-duration" yaml:"http-duration"`
	DNSStart              time.Time            `alias:"dns-start,omitempty" json:"dns-start,omitempty" xml:"dns-start,omitempty" yaml:"dns-start,omitempty"`
	DNSDone               time.Time            `alias:"dns-done,omitempty" json:"dns-done,omitempty" xml:"dns-done,omitempty" yaml:"dns-done,omitempty"`
	DNSDuration           time.Duration        `alias:"dns-duration,omitempty" json:"dns-duration,omitempty" xml:"dns-duration,omitempty" yaml:"dns-duration,omitempty"`
	DNSHost               string               `alias:"dns-host,omitempty" json:"dns-host,omitempty" xml:"dns-host,omitempty" yaml:"dns-host,omitempty"`
	DNSAddrs              []net.IPAddr         `alias:"dns-addrs,omitempty" json:"dns-addrs,omitempty" xml:"dns-addrs,omitempty" yaml:"dns-addrs,omitempty"`
	Connect               []ClientTraceConnect `alias:"connect" json:"connect" xml:"connect" yaml:"connect"`
	GetConn               time.Time            `alias:"get-conn" json:"get-conn" xml:"get-conn" yaml:"get-conn"`
	GetConnHostPort       string               `alias:"get-conn-host-port" json:"get-conn-host-port" xml:"get-conn-host-port" yaml:"get-conn-host-port"`
	GotConn               time.Time            `alias:"got-conn" json:"got-conn" xml:"got-conn" yaml:"got-conn"`
	GotFirstResponseByte  time.Time            `alias:"got-first-response-byte" json:"got-first-response-byte" xml:"got-first-response-byte" yaml:"got-first-response-byte"`
	TLSHandshakeStart     time.Time            `` /* 147-byte string literal not displayed */
	TLSHandshakeDone      time.Time            `` /* 143-byte string literal not displayed */
	TLSHandshakeDuration  time.Duration        `` /* 159-byte string literal not displayed */
	TLSHandshakeError     error                `` /* 147-byte string literal not displayed */
	TLSHandshakeIssuer    string               `` /* 151-byte string literal not displayed */
	TLSHandshakeSubject   string               `` /* 155-byte string literal not displayed */
	TLSHandshakeNotBefore time.Time            `` /* 167-byte string literal not displayed */
	TLSHandshakeNotAfter  time.Time            `` /* 163-byte string literal not displayed */
	TLSHandshakeDigest    string               `` /* 151-byte string literal not displayed */
	WroteHeaders          http.Header          `alias:"wrote-headers,omitempty" json:"wrote-headers,omitempty" xml:"wrote-headers,omitempty" yaml:"wrote-headers,omitempty"`
}

ClientTrace 定义http客户端请求追踪记录的数据。

type ClientTraceConnect

type ClientTraceConnect struct {
	Network  string        `alias:"network" json:"network" xml:"network" yaml:"network"`
	Address  string        `alias:"address" json:"address" xml:"address" yaml:"address"`
	Start    time.Time     `alias:"start" json:"start" xml:"start" yaml:"start"`
	Done     time.Time     `alias:"done,omitempty" json:"done,omitempty" xml:"done,omitempty" yaml:"done,omitempty"`
	Duration time.Duration `alias:"duration,omitempty" json:"duration,omitempty" xml:"duration,omitempty" yaml:"duration,omitempty"`
	Error    error         `alias:"error,omitempty" json:"error,omitempty" xml:"error,omitempty" yaml:"error,omitempty"`
}

ClientTraceConnect 定义Trace连接信息,一个请求可能出现多连接。

type Config

type Config interface {
	Get(string) any
	Set(string, any) error
	ParseOption(...ConfigParseFunc)
	Parse(context.Context) error
}

Config defines configuration management and uses configuration read-write and analysis functions.

Get/Set read and write data implementation:

Use custom struct or map as data storage
Support Lock concurrency safety
Access attributes based on string path hierarchy

The default analysis function implementation:

Custom configuration analysis function
Parse multiple json files
Parse the length and short parameters of the command line
Parse Env environment variables
Switch working directory
Generate help information based on the structure

Config 定义配置管理,使用配置读写和解析功能。

Get/Set读写数据实现下列功能:

使用自定义struct或map作为数据存储
支持Lock并发安全
基于字符串路径层次访问属性

默认解析函数实现下列功能:

自定义配置解析函数
解析多json文件
解析命令行长短参数
解析Env环境变量
切换工作目录
根据结构体生成帮助信息

func NewConfig

func NewConfig(data any) Config

NewConfig function creates a configStd. If the incoming parameter is empty, use map[string]any as metadata.

If the metadata type is map[string]any, use map to read and write key values, otherwise use eudore.Set and eudore.Get methods to read and write metadata.

If the incoming configuration object implements the same read-write lock method as sync.RLock, use the configured read-write lock, otherwise a sync.RWMutex lock will be created.

configStd has implemented the json.Marshaler and json.Unmarshaler interfaces.

NewConfig 函数创建一个configStd,如果传入参数为空,使用map[string]any作为元数据。

如果元数据类型为map[string]any使用map读写键值,否则其他类型使用eudore.Set和eudore.Get方法去读元写数据。

如果传入的配置对象实现sync.RLock一样的读写锁方法,则使用配置的读写锁,否则会创建一个sync.RWMutex锁。

configStd已实现json.Marshaler和json.Unmarshaler接口.

type ConfigParseFunc

type ConfigParseFunc func(context.Context, Config) error

ConfigParseFunc 定义配置解析函数。

Config 默认解析函数为eudore.ConfigAllParseFunc。

func NewConfigParseArgs

func NewConfigParseArgs(shortsmap map[string][]string) ConfigParseFunc

NewConfigParseArgs function uses the eudore.Set method to set the command line parameter data, and the command line parameter uses the format of'--{key}.{sub}={value}'.

Shortsmap is mapped as a short parameter. If the structure has a'flag' tag, it will be used as the abbreviation of the path. The tag length must be less than 5, the command line format is'-{short}={value}, and the short parameter will automatically be long parameter.

NewConfigParseArgs 函数使用eudore.Set方法设置命令行参数数据,命令行参数使用'--{key}.{sub}={value}'格式。

shortsmap作为短参数映射,如果结构体存在'flag' tag将作为该路径的缩写, tag长度需要小于5,命令行格式为'-{short}={value},短参数将会自动为长参数。

func NewConfigParseDefault

func NewConfigParseDefault() ConfigParseFunc

The NewConfigParseDefault function creates a default variable parsing function that gets the value from ENV to set the default variable.

NewConfigParseDefault 函数创建一个默认变量解析函数,从ENV获取值设置默认变量。

env to keys:

EUDORE_CONTEXT_MAX_HANDLER                => DefaultContextMaxHandler
EUDORE_CONTEXT_MAX_APPLICATION_FORM_SIZE  => DefaultContextMaxApplicationFormSize
EUDORE_CONTEXT_MAX_MULTIPART_FORM_MEMORY  => DefaultContextMaxMultipartFormMemory
EUDORE_CONTEXT_FORM_MAX_MEMORY            => DefaultContextFormMaxMemory
EUDORE_HANDLER_EMBED_CACHE_CONTROL        => DefaultHandlerEmbedCacheControl
EUDORE_HANDLER_EMBED_TIME                 => DefaultHandlerEmbedTime
EUDORE_LOGGER_DEPTH_MAX_STACK             => DefaultLoggerDepthMaxStack
EUDORE_LOGGER_ENABLE_HOOK_FATAL           => DefaultLoggerEnableHookFatal
EUDORE_LOGGER_ENABLE_HOOK_META            => DefaultLoggerEnableHookMeta
EUDORE_LOGGER_ENABLE_STD_COLOR            => DefaultLoggerEnableStdColor
EUDORE_LOGGER_ENTRY_BUFFER_LENGTH         => DefaultLoggerEntryBufferLength
EUDORE_LOGGER_ENTRY_FIELDS_LENGTH         => DefaultLoggerEntryFieldsLength
EUDORE_LOGGER_FORMATTER                   => DefaultLoggerFormatter
EUDORE_LOGGER_FORMATTER_FORMAT_TIME       => DefaultLoggerFormatterFormatTime
EUDORE_LOGGER_FORMATTER_KEY_LEVEL         => DefaultLoggerFormatterKeyLevel
EUDORE_LOGGER_FORMATTER_KEY_MESSAGE       => DefaultLoggerFormatterKeyMessage
EUDORE_LOGGER_FORMATTER_KEY_TIME          => DefaultLoggerFormatterKeyTime
EUDORE_LOGGER_WRITER_STDOUT_WINDOWS_COLOR => DefaultLoggerWriterStdoutWindowsColor
EUDORE_ROUTER_LOGGER_KIND                 => DefaultRouterLoggerKind
EUDORE_SERVER_READ_TIMEOUT                => DefaultServerReadTimeout
EUDORE_SERVER_READ_HEADER_TIMEOUT         => DefaultServerReadHeaderTimeout
EUDORE_SERVER_WRITE_TIMEOUT               => DefaultServerWriteTimeout
EUDORE_SERVER_IDLE_TIMEOUT                => DefaultServerIdleTimeout
EUDORE_SERVER_SHUTDOWN_WAIT               => DefaultServerShutdownWait
EUDORE_DAEMON_PIDFILE                     => DefaultDaemonPidfile
EUDORE_GODOC_SERVER                       => DefaultGodocServer
EUDORE_TRACE_SERVER                       => DefaultTraceServer

func NewConfigParseEnvFile

func NewConfigParseEnvFile(files ...string) ConfigParseFunc

The NewConfigParseEnvFile function creates an Env file configuration parsing method.

If a line of the Env file is in env format from the beginning, it will be loaded to the os as Env.

If the first character of the Env value is "'" as a multi-line value, until the end of a line also has "'"; Newline characters "\r\n" "\n" in multi-line values are replaced with "\n" and TrimSpace is performed.

If the Env value is an empty string, the Env will be deleted from os.

NewConfigParseEnvFile 函数创建Env文件配置解析方法。

如果Env文件一行从开始为env格式,则作为Env加载到os。

如果Env值为第一个字符为"'"作为多行值,直到一行结尾同样具有"'"; 多行值中的换行符"\r\n" "\n"被替换为"\n",并执行TrimSpace。

如果Env值为空字符串会从os删除这个Env。

example:

EUDORE_NAME=eudore
EUDORE_DEBUG=
EUDORE_KEY='
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----
'

func NewConfigParseEnvs

func NewConfigParseEnvs(prefix string) ConfigParseFunc

NewConfigParseEnvs function uses the eudore.Set method to set the environment variable data, usually the environment variable prefix uses'ENV_'.

Environment variables will be converted to lowercase paths, and the underscore of'_' is equivalent to the function of'.'.

NewConfigParseEnvs 函数使用eudore.Set方法设置环境变量数据,环境变量默认前缀使用'ENV_'。

环境变量将移除前缀转换成小写路径,'_'下划线相当于'.'的作用

exmapel: 'ENV_EUDORE_NAME=eudore' => 'eudore.name=eudore'。

func NewConfigParseHelp

func NewConfigParseHelp(key string) ConfigParseFunc

NewConfigParseHelp function if uses the structure configuration to output the'flag' and'description' tags to produce the default parameter description.

By default, only the parameter description is output. For other descriptions, please wrap the NewConfigParseHelp method.

Note that the properties of the configuration structure need to be non-empty, otherwise it will not enter the traversal.

NewConfigParseHelp 函数如果使用结构体配置输出'flag'和'description' tag生产默认参数描述。

默认仅输出参数描述,其他描述内容请包装NewConfigParseHelp方法。

注意配置结构体的属性需要是非空,否则不会进入遍历。

func NewConfigParseJSON

func NewConfigParseJSON(key string) ConfigParseFunc

NewConfigParseJSON method parses the json file configuration, usually the key is "config".

The configuration item value is string(';' divided into multiple paths) or []string, if the loaded file does not exist, the file will be ignored.

NewConfigParseJSON 方法解析json文件配置,通常使用key为"config"。

配置项值为string(';'分割为多路径)或[]string,如果加载文件不存在将忽略文件。

func NewConfigParseWorkdir

func NewConfigParseWorkdir(key string) ConfigParseFunc

NewConfigParseWorkdir function initializes the workspace, usually using the key as string("workdir") to obtain the workspace directory and switch.

NewConfigParseWorkdir 函数初始化工作空间,通常使用key为string("workdir"),获取工作空间目录并切换。

type Context

type Context interface {
	// context
	Reset(http.ResponseWriter, *http.Request)
	GetContext() context.Context
	Request() *http.Request
	Response() ResponseWriter
	Value(any) any
	SetContext(context.Context)
	SetRequest(*http.Request)
	SetResponse(ResponseWriter)
	SetValue(any, any)
	// handles
	SetHandler(int, HandlerFuncs)
	GetHandler() (int, HandlerFuncs)
	Next()
	End()
	Err() error

	// request info
	Read([]byte) (int, error)
	Host() string
	Method() string
	Path() string
	RealIP() string
	RequestID() string
	ContentType() string
	Istls() bool
	Body() []byte
	Bind(any) error

	// param query header cookie form
	Params() *Params
	GetParam(string) string
	SetParam(string, string)
	Querys() url.Values
	GetQuery(string) string
	GetHeader(string) string
	SetHeader(string, string)
	Cookies() []Cookie
	GetCookie(string) string
	SetCookie(*CookieSet)
	SetCookieValue(string, string, int)
	FormValue(string) string
	FormValues() map[string][]string
	FormFile(string) *multipart.FileHeader
	FormFiles() map[string][]*multipart.FileHeader

	// response
	Write([]byte) (int, error)
	WriteString(string) (int, error)
	WriteHeader(int)
	Redirect(int, string)
	Push(string, *http.PushOptions) error
	Render(any) error
	WriteFile(string)

	// Database interface
	Query(any, DatabaseStmt) error
	Exec(DatabaseStmt) error
	NewRequest(string, string, ...any) error
	// Logger interface
	Debug(...any)
	Info(...any)
	Warning(...any)
	Error(...any)
	Fatal(...any)
	Debugf(string, ...any)
	Infof(string, ...any)
	Warningf(string, ...any)
	Errorf(string, ...any)
	Fatalf(string, ...any)
	WithField(string, any) Logger
	WithFields([]string, []any) Logger
}

Context 定义请求上下文接口,分为请求上下文数据、请求、参数、响应、日志输出五部分。

context.Context、eudore.ResponseWriter、*http.Request、eudore.Logger对象读写
中间件机制执行
基本请求信息
数据Bind和Validate
重复读取请求body
param、query、header、cookie、form读写
状态码、header、重定向、push、body写入
数据写入Render
5级日志格带fields格式化属性

type Controller

type Controller interface {
	Inject(Controller, Router) error
}

Controller defines the controller interface.

The default AutoRoute controller implements the following functions:

The controller method maps the route method path.
Controller construction error delivery.
Custom controller function mapping relationship.
Custom controller routing group and routing parameters.
Controller routing combination, get the routing method of the combined controller.
Controller method composition, using the calling method controlled by the composition.

Controller 定义控制器接口。

默认AutoRoute控制器实现下列功能:

控制器方法映射路由方法路径。
控制器构造错误传递(NewControllerError)。
自定义控制器函数映射关系(实现'func ControllerRoute() map[string]string)')。
自定义控制器路由组和路由参数(实现'func ControllerParam(pkg, name, method string) string')。
控制器路由组合,获得被组合控制器的路由方法。
控制器方法组合,使用被组合控制的的调用方法。

func NewControllerError

func NewControllerError(ctl Controller, err error) Controller

NewControllerError function returns a controller error, and the corresponding error is returned when the controller Inject.

NewControllerError 函数返回一个控制器错误,在控制器Inject时返回对应的错误。

type ControllerAutoRoute

type ControllerAutoRoute struct{}

The ControllerAutoRoute implements the routing mapping controller to register the corresponding router method according to the method.

ControllerAutoRoute 实现路由映射控制器根据方法注册对应的路由器方法。

func (ControllerAutoRoute) Inject

func (ctl ControllerAutoRoute) Inject(controller Controller, router Router) error

Inject method implements the method of injecting the controller into the router, and the ControllerAutoRoute controller calls the ControllerInjectAutoRoute method to inject.

Inject 方法实现控制器注入到路由器的方法,ControllerAutoRoute控制器调用ControllerInjectAutoRoute方法注入。

type Cookie struct {
	Name  string
	Value string
}

Cookie 定义请求读取的cookie header的键值对数据存储。

func (Cookie) String

func (c Cookie) String() string

String 方法返回Cookie格式化字符串。

type CookieSet

type CookieSet = http.Cookie

CookieSet 定义响应设置的set-cookie header的数据生成。

type Database

type Database interface {
	AutoMigrate(interface{}) error
	Metadata(interface{}) interface{}
	Query(context.Context, interface{}, DatabaseStmt) error
	Exec(context.Context, DatabaseStmt) error
	Begin(ctx context.Context, opts *sql.TxOptions) (Database, error)
	Commit() error
	Rollback() error
}

Database 定义数据库操作方法。

func NewDatabase

func NewDatabase(interface{}) Database

NewDatabase 方法创建一个空Database。

type DatabaseBuilder

type DatabaseBuilder interface {
	Context() context.Context
	DriverName() string
	Metadata(interface{}) interface{}
	WriteStmts(...interface{})
	Result() (string, []interface{}, error)
}

DatabaseBuilder 定义数据库sql构建者。

type DatabaseStmt

type DatabaseStmt interface {
	Build(DatabaseBuilder)
}

DatabaseStmt 定义数据库规则块。

func NewDatabaseRuntime

func NewDatabaseRuntime(ctx Context, stmt DatabaseStmt) DatabaseStmt

type FilterData

type FilterData struct {
	Package string   `alias:"package" json:"package" xml:"package" yaml:"package"`
	Name    string   `alias:"name" json:"name" xml:"name" yaml:"name"`
	Checks  []string `alias:"checks" json:"checks" xml:"checks" yaml:"checks"`
	Modifys []string `alias:"modifys" json:"modifys" xml:"modifys" yaml:"modifys"`
}

FilterData defines Filter data matching objects and rules.

Package and Name define the filter structure object name, you can use '*' fuzzy matching.

Checks and Modifys define data matching and modification behavior functions. If Modifys is not defined, the entire data object will be empty.

FilterData 定义Filter数据匹配对象和规则。

Package和Name定义过滤结构体对象名称,可以使用'*'模糊匹配。

Checks和Modifys定义数据匹配和修改行为函数,如果未定义Modifys将整个数据对象置空。

type FuncCreateKind

type FuncCreateKind uint8

FuncCreateKind 定义FuncCreator可以创建的函数类型。

const (
	FuncCreateInvalid FuncCreateKind = iota
	FuncCreateString
	FuncCreateInt
	FuncCreateUint
	FuncCreateFloat
	FuncCreateBool
	FuncCreateAny
	FuncCreateSetString
	FuncCreateSetInt
	FuncCreateSetUint
	FuncCreateSetFloat
	FuncCreateSetBool
	FuncCreateSetAny
	FuncCreateNumber = FuncCreateAny
)

func NewFuncCreateKind

func NewFuncCreateKind(s string) FuncCreateKind

NewFuncCreateKind 函数解析FuncCreateKind字符串。

func NewFuncCreateKindWithType

func NewFuncCreateKindWithType(t reflect.Type) FuncCreateKind

NewFuncCreateKindWithType 函数类型创建FuncCreateKind。

func (FuncCreateKind) String

func (kind FuncCreateKind) String() string

type FuncCreator

type FuncCreator interface {
	RegisterFunc(string, ...any) error
	CreateFunc(FuncCreateKind, string) (any, error)
	List() []string
}

FuncCreator 定义校验函数构造器,默认由RouterStd、validate、filter使用。

func NewFuncCreator

func NewFuncCreator() FuncCreator

NewFuncCreator 函数创建默认FuncCreator并加载默认规则。

func NewFuncCreatorExpr

func NewFuncCreatorExpr() FuncCreator

NewFuncCreatorExpr 函数创建一个支持AND OR NOT关系表达式解析的FuncCreator。

func NewFuncCreatorWithContext

func NewFuncCreatorWithContext(ctx context.Context) FuncCreator

NewFuncCreatorWithContext 函数从环境上下文创建FuncCreator。

type FuncRunner

type FuncRunner struct {
	Kind FuncCreateKind
	Func any
}

FuncRunner 定义创建函数类型和地址信息。

func (*FuncRunner) Run

func (fn *FuncRunner) Run(v reflect.Value) bool

Run 执行任意函数。

func (*FuncRunner) RunPtr

func (fn *FuncRunner) RunPtr(v reflect.Value) bool

RunPtr executes any function, dereferences the Ptr type, and executes each value of Slice and Array.

RunPtr 执行任意函数,对Ptr类型会解除引用,对Slice和Array每一个值进行执行。

type GetWarp

type GetWarp func(string) any

GetWarp 对象封装Get函数提供类型转换功能。

func NewGetWarp

func NewGetWarp(fn func(string) any) GetWarp

NewGetWarp 函数创建一个getwarp处理类型转换。

func NewGetWarpWithApp

func NewGetWarpWithApp(app *App) GetWarp

NewGetWarpWithApp 函数使用App创建getwarp。

func NewGetWarpWithConfig

func NewGetWarpWithConfig(c Config) GetWarp

NewGetWarpWithConfig 函数使用Config.Get创建getwarp。

func NewGetWarpWithMapString

func NewGetWarpWithMapString(data map[string]any) GetWarp

NewGetWarpWithMapString 函数使用map[string]any创建getwarp。

func NewGetWarpWithObject

func NewGetWarpWithObject(obj any) GetWarp

NewGetWarpWithObject 函数使用map或创建getwarp。

func (GetWarp) GetAny

func (fn GetWarp) GetAny(key string) any

GetAny 方法获取any类型的配置值。

func (GetWarp) GetBool

func (fn GetWarp) GetBool(key string) bool

GetBool 方法获取bool类型的配置值。

func (GetWarp) GetFloat32

func (fn GetWarp) GetFloat32(key string, vals ...float32) float32

GetFloat32 方法取获取float32类型的配置值。

func (GetWarp) GetFloat64

func (fn GetWarp) GetFloat64(key string, vals ...float64) float64

GetFloat64 方法取获取float64类型的配置值。

func (GetWarp) GetInt

func (fn GetWarp) GetInt(key string, vals ...int) int

GetInt 方法获取int类型的配置值。

func (GetWarp) GetInt64

func (fn GetWarp) GetInt64(key string, vals ...int64) int64

GetInt64 方法int64类型的配置值。

func (GetWarp) GetString

func (fn GetWarp) GetString(key string, vals ...string) string

GetString 方法获取一个字符串,如果字符串为空返回其他默认非空字符串。

func (GetWarp) GetUint

func (fn GetWarp) GetUint(key string, vals ...uint) uint

GetUint 方法取获取uint类型的配置值。

func (GetWarp) GetUint64

func (fn GetWarp) GetUint64(key string, vals ...uint64) uint64

GetUint64 方法取获取uint64类型的配置值。

type HandlerDataFunc

type HandlerDataFunc = func(Context, any) error

HandlerDataFunc defines the request context data processing function.

Define four behaviors of Bind Validater Filter Render by default.

Binder object is used to request data deserialization, By default, data is parsed according to the request data format specified by the Content-Type header of the http request.

The Renderer object accepts the header to select the data object serialization method. HandlerDataFunc 定义请求上下文数据处理函数。

默认定义Bind Validater Filter Render四种行为。

Binder对象用于请求数据反序列化, 默认根据http请求的Content-Type header指定的请求数据格式来解析数据。

Renderer对象更加Accept Header选择数据对象序列化的方法。

func NewBindWithHeader

func NewBindWithHeader(fn HandlerDataFunc) HandlerDataFunc

NewBindWithHeader implements Bind to additionally encapsulate bind header.

NewBindWithHeader 实现Bind额外封装bind header。

func NewBindWithURL

func NewBindWithURL(fn HandlerDataFunc) HandlerDataFunc

NewBindWithURL implements Bind and also executes BindURL when HeaderContentType is not empty.

NewBindWithURL 实现Bind在HeaderContentType非空时也执行BindURL。

func NewBinds

func NewBinds(binds map[string]HandlerDataFunc) HandlerDataFunc

The NewBinds method defines the ContentType Header mapping Bind function.

NewBinds 方法定义ContentType Header映射Bind函数。

func NewFilterRules

func NewFilterRules(c context.Context) HandlerDataFunc

NewFilterRules function creates FilterData filter function.

Load filter rules from ctx.Value(ContextKeyFilterRules).

NewFilterRules 函数创建FilterData过滤函数。

从ctx.Value(ContextKeyFilterRules)加载过滤规则。

func NewRenders

func NewRenders(renders map[string]HandlerDataFunc) HandlerDataFunc

The NewRenders method defines the default HeaderAccept value mapping Render function.

The HeaderAccept value ignores non-zero weight values, and the order takes precedence.

NewRenders 方法定义默认HeaderAccept值映射Render函数。

HeaderAccept值忽略非零权重值,顺序优先。

func NewValidateField

func NewValidateField(ctx context.Context) HandlerDataFunc

The NewValidateField method creates a struct property validator.

Get ContextKeyFuncCreator.(FuncCreator) to create a verification function. Use the structure tag validate to get the verification function from FuncCreator.

Allowed types are struct []struct []*struct []interface.

Only verify that the field type is string/int/uint/float/bool/any, and the int-related numerical type is converted to int and then verified, and the precision may be lost.

NewValidateField 方法创建结构体属性校验器。

获取ContextKeyFuncCreator.(FuncCreator)用于创建校验函数。 使用结构体tag validate从FuncCreator获取校验函数。

允许类型为struct []struct []*struct []interface。

仅校验字段类型为string/int/uint/float/bool/any,int相关数值类型转换成int后校验,可能精度丢失。

type HandlerExtender

type HandlerExtender interface {
	RegisterExtender(string, any) error
	CreateHandler(string, any) HandlerFuncs
	List() []string
}

HandlerExtender defines the method of extending the function handler.

The HandlerExtender object has three default implementations, Base, Warp, and Tree, which are defined in the HandlerExtender interface.

HandlerExtender 定义函数扩展处理者的方法。

HandlerExtender默认拥有Base、Warp、Tree三种实现,具体参数三种对象的文档。

func NewHandlerExtender

func NewHandlerExtender() HandlerExtender

NewHandlerExtender 函数创建默认HandlerExtender并加载默认扩展函数。

func NewHandlerExtenderBase

func NewHandlerExtenderBase() HandlerExtender

NewHandlerExtenderBase method returns a basic function extension processing object.

The NewHandlerExtenderBase().RegisterExtender method registers a conversion function and ignores the path.

The NewHandlerExtenderBase().CreateHandler method implementation creates multiple request handler functions, ignoring paths.

NewHandlerExtenderBase 方法返回一个基本的函数扩展处理对象。

NewHandlerExtenderBase().RegisterExtender 方法实现注册一个转换函数,忽略路径。

NewHandlerExtenderBase().CreateHandler 方法实现创建多个请求处理函数,忽略路径。

func NewHandlerExtenderTree

func NewHandlerExtenderTree() HandlerExtender

NewHandlerExtenderTree function creates a path-based function extender.

Mainly implement path matching. All actions are processed by the node's HandlerExtender, and the NewHandlerExtenderBase () object is used.

All registration and creation actions will be performed by matching the lowest node of the tree. If it cannot be created, the tree nodes will be processed upwards in order.

The NewHandlerExtenderTree().RegisterExtender method registers a handler function based on the path, and initializes to NewHandlerExtenderBase () if the HandlerExtender is empty.

The NewHandlerExtenderTree().CreateHandler method matches the child nodes of the tree based on the path, and then executes the CreateHandler method from the most child node up. If it returns non-null, it returns directly.

NewHandlerExtenderTree 函数创建一个基于路径的函数扩展者。

主要实现路径匹配,所有行为使用节点的HandlerExtender处理,使用NewHandlerExtenderBase()对象。

所有注册和创建行为都会匹配树最下级节点执行,如果无法创建则在树节点依次向上处理。

NewHandlerExtenderTree().RegisterExtender 方法基于路径注册一个处理函数, 如果HandlerExtender为空则初始化为NewHandlerExtenderBase()。

NewHandlerExtenderTree().CreateHandler 方法基于路径向树子节点匹配, 后从最子节点依次向上执行CreateHandler方法,如果返回非空直接返回,否在会依次执行注册行为。

func NewHandlerExtenderWarp

func NewHandlerExtenderWarp(base, last HandlerExtender) HandlerExtender

NewHandlerExtenderWarp function creates a chained HandlerExtender object.

All objects are registered and created using base. If base cannot create a function handler, use last to create a function handler.

The NewHandlerExtenderWarp(base, last).RegisterExtender method uses the base object to register extension functions.

The NewHandlerExtenderWarp(base, last).CreateHandler method first uses the base object to create multiple request processing functions. If it returns nil, it uses the last object to create multiple request processing functions.

NewHandlerExtenderWarp 函数创建一个链式HandlerExtender对象。

所有对象注册和创建均使用base,如果base无法创建函数处理者则使用last创建函数处理者。

NewHandlerExtenderWarp(base, last).RegisterExtender 方法使用base对象注册扩展函数。

NewHandlerExtenderWarp(base, last).CreateHandler 方法先使用base对象创建多个请求处理函数, 如果返回nil,则使用last对象创建多个请求处理函数。

func NewHandlerExtenderWithContext

func NewHandlerExtenderWithContext(ctx context.Context) HandlerExtender

type HandlerFunc

type HandlerFunc func(Context)

HandlerFunc is a function that processes a Context.

HandlerFunc 是处理一个Context的函数。

func NewHandlerEmbed

func NewHandlerEmbed(fs iofs.FS) HandlerFunc

NewHandlerEmbed 函数创建iofs.FS扩展函数。

func NewHandlerFunc

func NewHandlerFunc(fn func()) HandlerFunc

NewHandlerFunc 函数处理func()。

func NewHandlerFuncContextAnyError

func NewHandlerFuncContextAnyError(fn any) HandlerFunc

NewHandlerFuncContextAnyError 函数处理func(Context) (T, error)返回数据渲染和error处理。

func NewHandlerFuncContextError

func NewHandlerFuncContextError(fn func(Context) error) HandlerFunc

NewHandlerFuncContextError 函数处理func(Context) error返回的error处理。

func NewHandlerFuncContextRender

func NewHandlerFuncContextRender(fn func(Context) any) HandlerFunc

NewHandlerFuncContextRender 函数处理func(Context) any返回数据渲染。

func NewHandlerFuncContextRenderError

func NewHandlerFuncContextRenderError(fn func(Context) (any, error)) HandlerFunc

NewHandlerFuncContextRenderError 函数处理func(Context) (any, error)返回数据渲染和error处理。

func NewHandlerFuncError

func NewHandlerFuncError(fn func() error) HandlerFunc

NewHandlerFuncError 函数处理func() error返回的error处理。

func NewHandlerFuncRPC

func NewHandlerFuncRPC(fn any) HandlerFunc

NewHandlerFuncRPC function needs to pass in a function that returns a request for processing and is dynamically called by reflection.

Function form: func (Context, Request) (Response, error)

The types of Request and Response can be map or struct or pointer to struct. All 4 parameters need to exist, and the order cannot be changed.

NewHandlerFuncRPC 函数需要传入一个函数,返回一个请求处理,通过反射来动态调用。

函数形式: func(Context, Request) (Response, error)

Request和Response的类型可以为map或结构体或者结构体的指针,4个参数需要全部存在,且不可调换顺序。

func NewHandlerFuncRPCMap

func NewHandlerFuncRPCMap(fn func(Context, map[string]any) (any, error)) HandlerFunc

NewHandlerFuncRPCMap defines a fixed request and response to function processing of type map [string] interface {}.

is a subset of NewRPCHandlerFunc and has type restrictions, but using map [string] interface {} to save requests does not use reflection.

NewHandlerFuncRPCMap 定义了固定请求和响应为map[string]any类型的函数处理。

是NewRPCHandlerFunc的一种子集,拥有类型限制,但是使用map[string]any保存请求没用使用反射。

func NewHandlerFuncRender

func NewHandlerFuncRender(fn func() any) HandlerFunc

NewHandlerFuncRender 函数处理func() any。

func NewHandlerFuncRenderError

func NewHandlerFuncRenderError(fn func() (any, error)) HandlerFunc

NewHandlerFuncRenderError 函数处理func() (any, error)返回数据渲染和error处理。

func NewHandlerFuncString

func NewHandlerFuncString(fn func() string) HandlerFunc

NewHandlerFuncString 函数处理func() string,然后指定函数生成的字符串。

func NewHandlerHTTP

func NewHandlerHTTP(h handlerHTTP) HandlerFunc

NewHandlerHTTP 函数handlerHTTP接口转换成HandlerFunc。

func NewHandlerHTTPFileSystem

func NewHandlerHTTPFileSystem(fs http.FileSystem) HandlerFunc

NewHandlerHTTPFileSystem 函数创建http.FileSystem扩展函数。

func NewHandlerHTTPFunc1

func NewHandlerHTTPFunc1(fn http.HandlerFunc) HandlerFunc

NewHandlerHTTPFunc1 函数转换处理http.HandlerFunc类型。

func NewHandlerHTTPFunc2

func NewHandlerHTTPFunc2(fn func(http.ResponseWriter, *http.Request)) HandlerFunc

NewHandlerHTTPFunc2 函数转换处理func(http.ResponseWriter, *http.Request)类型。

func NewHandlerHTTPHandler

func NewHandlerHTTPHandler(h http.Handler) HandlerFunc

NewHandlerNetHTTP 函数转换处理http.Handler对象。

func NewHandlerStatic

func NewHandlerStatic(dirs ...any) HandlerFunc

NewHandlerStatic 函数使用多个any值创建混合静态文件处理函数。

func NewHandlerStringer

func NewHandlerStringer(fn fmt.Stringer) HandlerFunc

NewHandlerStringer 函数处理fmt.Stringer接口类型转换成HandlerFunc。

func (HandlerFunc) String

func (h HandlerFunc) String() string

String method implements the fmt.Stringer interface and implements the output function name.

String 方法实现fmt.Stringer接口,实现输出函数名称。

type HandlerFuncs

type HandlerFuncs []HandlerFunc

HandlerFuncs is a collection of HandlerFunc, representing multiple request processing functions.

HandlerFuncs 是HandlerFunc的集合,表示多个请求处理函数。

func NewHandlerFuncsCombine

func NewHandlerFuncsCombine(hs1, hs2 HandlerFuncs) HandlerFuncs

NewHandlerFuncsCombine function merges two HandlerFuncs into one. The default maximum length is now 63, which exceeds panic.

Used to reconstruct the slice and prevent the appended data from being confused.

HandlerFuncsCombine 函数将两个HandlerFuncs合并成一个,默认现在最大长度63,超过过panic。

用于重构切片,防止切片append数据混乱。

func NewHandlerFuncsFilter

func NewHandlerFuncsFilter(hs HandlerFuncs) HandlerFuncs

NewHandlerFuncsFilter 函数过滤掉多个请求上下文处理函数中的空对象。

type Logger

type Logger interface {
	Debug(...any)
	Info(...any)
	Warning(...any)
	Error(...any)
	Fatal(...any)
	Debugf(string, ...any)
	Infof(string, ...any)
	Warningf(string, ...any)
	Errorf(string, ...any)
	Fatalf(string, ...any)
	WithField(string, any) Logger
	WithFields([]string, []any) Logger
	GetLevel() LoggerLevel
	SetLevel(LoggerLevel)
}

Logger defines a log output interface to implement the following functions:

Five-level log format output
Log entries with Fields attribute
json/text ordered formatted output
Custom processing Hook
Expression filter log
Initialize log processing
Standard output stream displays colored Level
Set file line information output
Log file soft link
log file rollover
log file cleanup

Logger 定义日志输出接口实现下列功能:

五级日志格式化输出
日志条目带Fields属性
json/text有序格式化输出
自定义处理Hook
表达式过滤日志
初始化日志处理
标准输出流显示彩色Level
设置文件行信息输出
日志文件软连接
日志文件滚动
日志文件清理

func NewLogger

func NewLogger(config *LoggerConfig) Logger

NewLogger 创建一个标准日志处理器。

默认配置:

&LoggerConfig{
	Stdout:    true,
	StdColor:  DefaultLoggerEnableStdColor,
	HookFatal: DefaultLoggerEnableHookFatal,
	HookMeta:  DefaultLoggerEnableHookMeta,
}

func NewLoggerInit

func NewLoggerInit() Logger

NewLoggerInit The initial log processor only records logs, and gets a new Logger to process logs when Unmount.

If the subsequent Logger is not set after LoggerInit is set, App.Run() must be called to release the log in LoggerInit.

NewLoggerInit 初始日志处理器仅记录日志,在Unmount时获取新Logger处理日志.

在设置LoggerInit后未设置后续Logger,必须调用App.Run()将LoggerInit内日志释放出来。

func NewLoggerNull

func NewLoggerNull() Logger

NewLoggerNull 定义空日志输出,丢弃所有日志。

func NewLoggerWithContext

func NewLoggerWithContext(ctx context.Context) Logger

NewLoggerWithContext 方法从环境上下文ContextKeyLogger获取Logger,如果无法获取Logger返回DefaultLoggerNull对象。

type LoggerConfig

type LoggerConfig struct {
	// 设置额外的LoggerHandler,和配置初始化创建的Handlers排序后处理LoggerEntry。
	Handlers []LoggerHandler `alias:"handlers" json:"-" xml:"-" yaml:"-"`
	// 设置日志输出级别。
	Level LoggerLevel `alias:"level" json:"level" xml:"level" yaml:"level"`
	// 是否记录调用者信息。
	Caller bool `alias:"caller" json:"caller" xml:"caller" yaml:"caller"`
	// 设置Entry输出格式,默认值为json,
	// 如果为json/text启用NewLoggerFormatterJSON/NewLoggerFormatterText。
	Formatter string `alias:"formater" json:"formater" xml:"formater" yaml:"formater"`
	// 设置日志时间输出格式,默认值为DefaultLoggerFormatterFormatTime或time.RFC3339。
	TimeFormat string `alias:"timeformat" json:"timeformat" xml:"timeformat" yaml:"timeformat"`
	// 设置Entry过滤规则;如果非空启用NewLoggerHookFilter。
	HookFilter [][]string `alias:"hoolfilter" json:"hoolfilter" xml:"hoolfilter" yaml:"hoolfilter"`
	// 是否处理Fatal级别日志,调用应用结束方法;如果为true启用NewLoggerHookMeta。
	HookFatal bool `alias:"hookfatal" json:"hookfatal" xml:"hookfatal" yaml:"hookfatal"`
	// 是否采集Meta信息,记录日志count、size;如果为true启用NewLoggerHookFatal。
	HookMeta bool `alias:"hookmeta" json:"hookmeta" xml:"hookmeta" yaml:"hookmeta"`
	// 是否输出日志到os.Stdout标准输出流;如果存在Env EnvEudoreDaemonEnable时会强制修改为false;
	// 如果为true启动NewLoggerWriterStdout。
	Stdout bool `alias:"stdout" json:"stdout" xml:"stdout" yaml:"stdout"`
	// 是否输出日志时使用彩色Level,默认在windows系统下禁用。
	StdColor bool `alias:"stdcolor" json:"stdcolor" xml:"stdcolor" yaml:"stdcolor"`
	// 设置日志文件输出路径;如果非空启用NewLoggerWriterFile,
	// 如果Path包含关键字yyyy/mm/dd/hh或MaxSize非0则改为启用NewLoggerWriterRotate。
	Path string `alias:"path" json:"path" xml:"path" yaml:"path" description:"Output file path."`
	// 设置日志文件滚动size,在文件名后缀之前添加索引值。
	MaxSize uint64 `alias:"maxsize" json:"maxsize" xml:"maxsize" yaml:"maxsize" description:"roatte file max size"`
	// 设置日志文件最多保留天数,如果非0使用hookFileRecycle。
	MaxAge int `alias:"maxage" json:"maxage" xml:"maxage" yaml:"maxage"`
	// 设置日志文件最多保留数量,如果非0使用hookFileRecycle。
	MaxCount int `alias:"maxcount" json:"maxcount" xml:"maxcount" yaml:"maxcount"`
	// 设置日志文件软链接名称,如果非空使用hookFileLink。
	Link string `alias:"link" json:"link" xml:"link" yaml:"link" description:"Output file link to path."`
}

LoggerConfig 定义loggerStd配置信息。

type LoggerEntry

type LoggerEntry struct {
	Level   LoggerLevel
	Time    time.Time
	Message string
	Keys    []string
	Vals    []any
	Buffer  []byte
}

LoggerEntry 定义日志条目数据对象。

type LoggerHandler

type LoggerHandler interface {
	HandlerPriority() int
	HandlerEntry(*LoggerEntry)
}

LoggerHandler 定义LoggerEntry处理方法

HandlerPriority 方法返回Handler处理顺序,小值优先。

HandlerEntry 方法处理Entry内容,设置Level=LoggerDiscard后结束后续处理。

func NewLoggerFormatterJSON

func NewLoggerFormatterJSON(timeformat string) LoggerHandler

NewLoggerStdDataJSON 函数创建一个LoggerStd的JSON数据处理器。

如果设置EnvEudoreDaemonEnable表示为后台运行,非终端启动会自动设置Std=false; 在非windows系统下,仅输出到终端不输出到文件时Level关键字会设置为彩色。

func NewLoggerFormatterText

func NewLoggerFormatterText(timeformat string) LoggerHandler

NewLoggerFormatterText 函数创建文件行格式日志格式化。

func NewLoggerHookFatal

func NewLoggerHookFatal(fn func(*LoggerEntry)) LoggerHandler

NewLoggerHookFatal 函数创建Fatal级别日志处理Hook。

func NewLoggerHookFilter

func NewLoggerHookFilter(rules [][]string) LoggerHandler

NewLoggerHookFilter 函数创建日志过滤处理器。

在Mount时如果规则初始化失败,查看FuncCreator的Metadata。

func NewLoggerHookMeta

func NewLoggerHookMeta() LoggerHandler

NewLoggerHookMeta 函数创建日志Meta处理,记录日志数量和写入量。

func NewLoggerWriterFile

func NewLoggerWriterFile(name string) (LoggerHandler, error)

NewLoggerWriterFile 函数创建一个文件输出的日志写入流。

func NewLoggerWriterRotate

func NewLoggerWriterRotate(name string, maxsize uint64, fn ...func(string, string)) (LoggerHandler, error)

NewLoggerWriterRotate 函数创建一个支持文件切割的的日志写入流。

如果设置maxsize或name包含字符串yyyy/yy/mm/dd/hh,将可以滚动日志文件。

func NewLoggerWriterStdout

func NewLoggerWriterStdout(color bool) LoggerHandler

type LoggerLevel

type LoggerLevel int32

LoggerLevel 定义日志级别。

const (
	LoggerDebug LoggerLevel = iota
	LoggerInfo
	LoggerWarning
	LoggerError
	LoggerFatal
	LoggerDiscard
)

枚举使用的日志级别。

func (LoggerLevel) MarshalText

func (l LoggerLevel) MarshalText() ([]byte, error)

MarshalText 方法实现encoding.TextMarshaler接口,用于编码日志级别。

func (LoggerLevel) String

func (l LoggerLevel) String() string

String 方法实现ftm.Stringer接口,格式化输出日志级别。

func (*LoggerLevel) UnmarshalText

func (l *LoggerLevel) UnmarshalText(text []byte) error

UnmarshalText 方法实现encoding.TextUnmarshaler接口,用于解码日志级别。

type MetadataConfig

type MetadataConfig struct {
	Health bool   `alias:"health" json:"health" xml:"health" yaml:"health"`
	Name   string `alias:"name" json:"name" xml:"name" yaml:"name"`
	Error  error  `alias:"error,omitempty" json:"error,omitempty" xml:"error,omitempty" yaml:"error,omitempty"`
}

type MetadataFuncCreator

type MetadataFuncCreator struct {
	Health bool     `alias:"health" json:"health" xml:"health" yaml:"health"`
	Name   string   `alias:"name" json:"name" xml:"name" yaml:"name"`
	Funcs  []string `alias:"funcs" json:"funcs" xml:"funcs" yaml:"funcs"`
	Exprs  []string `alias:"exprs,omitempty" json:"exprs,omitempty" xml:"exprs,omitempty" yaml:"exprs,omitempty"`
	Errors []string `alias:"errors,omitempty" json:"errors,omitempty" xml:"errors,omitempty" yaml:"errors,omitempty"`
}

type MetadataHandlerExtender

type MetadataHandlerExtender struct {
	Health   bool     `alias:"health" json:"health" xml:"health" yaml:"health"`
	Name     string   `alias:"name" json:"name" xml:"name" yaml:"name"`
	Extender []string `alias:"extender" json:"extender" xml:"extender" yaml:"extender"`
}

type MetadataLogger

type MetadataLogger struct {
	Health     bool      `alias:"health" json:"health" xml:"health" yaml:"health"`
	Name       string    `alias:"name" json:"name" xml:"name" yaml:"name"`
	Count      [5]uint64 `alias:"count" json:"count" xml:"count" yaml:"count"`
	Size       uint64    `alias:"size" json:"size" xml:"size" yaml:"size"`
	SizeFormat string    `alias:"sizeformat" json:"sizeformat" xml:"sizeformat" yaml:"sizeformat"`
}

type MetadataRouter

type MetadataRouter struct {
	Health       bool       `alias:"health" json:"health" xml:"health" yaml:"health"`
	Name         string     `alias:"name" json:"name" xml:"name" yaml:"name"`
	Core         any        `alias:"core" json:"core" xml:"core" yaml:"core"`
	Errors       []string   `alias:"errors,omitempty" json:"errors,omitempty" xml:"errors,omitempty" yaml:"errors,omitempty"`
	Methods      []string   `alias:"methods" json:"methods" xml:"methods" yaml:"methods"`
	Paths        []string   `alias:"paths" json:"paths" xml:"paths" yaml:"paths"`
	Params       []Params   `alias:"params" json:"params" xml:"params" yaml:"params"`
	HandlerNames [][]string `alias:"handlernames" json:"handlernames" xml:"handlernames" yaml:"handlernames"`
}

type MetadataServer

type MetadataServer struct {
	Health     bool     `alias:"health" json:"health" xml:"health" yaml:"health"`
	Name       string   `alias:"name" json:"name" xml:"name" yaml:"name"`
	Ports      []string `alias:"ports" json:"ports" xml:"ports" yaml:"ports"`
	ErrorCount int64    `alias:"errorcount" json:"errorcount" xml:"errorcount" yaml:"errorcount"`
}

type Params

type Params []string

Params 定义用于保存一些键值数据。

func NewParamsRoute

func NewParamsRoute(path string) Params

NewParamsRoute 方法根据一个路由路径创建Params,支持路由路径块模式。

func (Params) Add

func (p Params) Add(vals ...string) Params

Add 方法添加一个参数。

func (Params) Clone

func (p Params) Clone() Params

Clone 方法深复制一个ParamArray对象。

func (Params) CombineWithRoute

func (p Params) CombineWithRoute(params Params) Params

CombineWithRoute 方法将params数据合并到p,用于路由路径合并。

func (Params) Del

func (p Params) Del(key string)

Del 方法删除一个参数值。

func (Params) Get

func (p Params) Get(key string) string

Get 方法返回一个参数的值。

func (Params) MarshalJSON

func (p Params) MarshalJSON() ([]byte, error)

MarshalJSON 方法设置Params json序列化显示的数据。

func (Params) Set

func (p Params) Set(key, val string) Params

Set 方法设置一个参数的值。

func (Params) String

func (p Params) String() string

String 方法输出Params成字符串。

type ProtobufDecoder

type ProtobufDecoder struct {
	Reader    *bufio.Reader
	N         int
	Err       error
	LastSlice map[reflect.Value]int
	// contains filtered or unexported fields
}

ProtobufDecoder 定义protobuf解码器

func NewProtobufDecoder

func NewProtobufDecoder(r io.Reader) *ProtobufDecoder

NewProtobufDecoder 方法创建一个protobuf解码器。

func (*ProtobufDecoder) Decode

func (dec *ProtobufDecoder) Decode(i interface{}) error

Decode 方法执行解码操作,如果存在数据异常会直接中止解析,会从结构体和tag中获取对应的proto信息。

type ProtobufEncoder

type ProtobufEncoder struct {
	io.Writer
	// contains filtered or unexported fields
}

ProtobufEncoder 定义protobuf编码器

func NewProtobufEncoder

func NewProtobufEncoder(w io.Writer) *ProtobufEncoder

NewProtobufEncoder 函数创建一个protobuf编码器。

func (*ProtobufEncoder) Encode

func (enc *ProtobufEncoder) Encode(i interface{}) error

Encode 方法执行probubuf编码,会从结构体和tag中获取对应的proto信息。

func (*ProtobufEncoder) SizeMessage

func (enc *ProtobufEncoder) SizeMessage(i interface{}) uint64

SizeMessage 方法计算一个对象编码后的长度。

type ResponseWriter

type ResponseWriter interface {
	// http.ResponseWriter
	Write([]byte) (int, error)
	WriteString(string) (int, error)
	WriteHeader(int)
	Header() http.Header
	// http.Flusher
	Flush()
	// http.Hijacker
	Hijack() (net.Conn, *bufio.ReadWriter, error)
	// http.Pusher
	Push(string, *http.PushOptions) error

	Size() int
	Status() int
}

ResponseWriter 接口用于写入http请求响应体status、header、body。

net/http.response实现了flusher、hijacker、pusher接口。

type Router

type Router interface {
	RouterCore
	// RouterMethod method
	Group(string) Router
	Params() *Params
	AddHandler(string, string, ...any) error
	AddController(...Controller) error
	AddMiddleware(...any) error
	AddHandlerExtend(...any) error
	AnyFunc(string, ...any)
	GetFunc(string, ...any)
	PostFunc(string, ...any)
	PutFunc(string, ...any)
	DeleteFunc(string, ...any)
	HeadFunc(string, ...any)
	PatchFunc(string, ...any)
}

Router interface is divided into RouterCore and RouterMethod. RouterCore implements router matching algorithm and logic, and RouterMethod implements the encapsulation of routing rule registration.

RouterCore implements route matching details. RouterMethod calls RouterCore to provide methods for external use.

RouterMethod The default directly registered interface of the route. Set the routing parameters, group routing, middleware, function extensions, controllers and other behaviors.

Do not use the RouterCore method to register routes directly at any time. You should use the Add ... method of RouterMethod.

RouterMethod implements the following functions:

Group routing
The middleware or function extension is registered in the local scope/global scope
Add controller
Display routing registration debug information

RouterCore has four router cores to implement the following functions:

High performance (70%-90% of httprouter performance, using less memory)
Low code complexity (RouterCoreStd supports 5 levels of priority, a code complexity of 19 is not satisfied)
Request for additional default parameters (including current routing matching rules)
Extend custom routing methods
Variable and wildcard matching
Matching priority Constant > Variable verification > Variable > Wildcard verification > Wildcard
Method priority Specify method > Any method (The specified method will override the Any method, and vice versa)
Variables and wildcards support regular and custom functions to verify data
Variables and wildcards support constant prefix
Get all registered routing rule information
Routing rule matching based on Host (implemented by RouterCoreHost)
Allows dynamic addition and deletion of router rules at runtime (RouterCoreStd implementation)

Router 接口分为RouterCore和RouterMethod,RouterCore实现路由器匹配算法和逻辑,RouterMethod实现路由规则注册的封装。

RouterCore实现路由匹配细节,RouterMethod调用RouterCore提供对外使用的方法。

RouterMethod 路由默认直接注册的接口,设置路由参数、组路由、中间件、函数扩展、控制器等行为。

任何时候请不要使用RouterCore的方法直接注册路由,应该使用RouterMethod的Add...方法。

RouterMethod实现下列功能:

组路由
中间件或函数扩展注册在局部作用域/全局作用域
添加控制器
显示路由注册debug信息

RouterCore拥有四种路由器核心实现下列功能:

高性能(httprouter性能的70%-90%,使用更少的内存)
低代码复杂度(RouterCoreStd支持5级优先级 一处代码复杂度19不满足)
请求获取额外的默认参数(包含当前路由匹配规则)
扩展自定义路由方法
变量和通配符匹配
匹配优先级 常量 > 变量校验 > 变量 > 通配符校验 > 通配符(RouterCoreStd五级优先级)
方法优先级 指定方法 > Any方法(指定方法会覆盖Any方法,反之不行)
变量和通配符支持正则和自定义函数进行校验数据
变量和通配符支持常量前缀
获取注册的全部路由规则信息
基于Host进行路由规则匹配(RouterCoreHost实现)
允许运行时进行动态增删路由器规则(RouterCoreStd实现,外层需要RouterCoreLock包装一层)

func NewRouter

func NewRouter(core RouterCore) Router

NewRouter method uses a RouterCore to create a Router object.

RouterStd implements RouterMethod interface registration related details, and routing matching is implemented by RouterCore.

NewRouter 方法使用一个RouterCore创建Router对象。

Router实现RouterMethod接口注册相关细节,路由匹配由RouterCore实现。

type RouterCore

type RouterCore interface {
	HandleFunc(string, string, HandlerFuncs)
	Match(string, string, *Params) HandlerFuncs
}

The RouterCore interface performs registration of the route and matches a request and returns the handler.

RouterCore mainly implements routing matching related details.

RouterCore接口,执行路由的注册和匹配一个请求并返回处理者。

RouterCore主要实现路由匹配相关细节。

func NewRouterCoreHost

func NewRouterCoreHost(fn func(string) RouterCore) RouterCore

NewRouterCoreHost function creates a Host routing core, and a function that creates a routing core based on the host value needs to be given.

If the parameter is empty, each route Host will create NewRouterCoreStd by default.

NewRouterCoreHost 函数创建一个Host路由核心,需要给定一个根据host值创建路由核心的函数。

如果参数为空默认每个路由Host都创建NewRouterCoreStd。

func NewRouterCoreLock

func NewRouterCoreLock(core RouterCore) RouterCore

NewRouterCoreLock function creates a router core with a read-write lock, and other router cores use the Lock core package when they need to dynamically modify the rules.

NewRouterCoreLock 函数创建一个带读写锁的路由器核心,其他路由器核心在需要动态修改规则时使用Lock核心包装。

func NewRouterCoreStd

func NewRouterCoreStd() RouterCore

NewRouterCoreStd function creates a Std router core and uses radix to match. For the function description, please refer to the Router document.

NewRouterCoreStd 函数创建一个Std路由器核心,使用radix匹配,功能说明见Router文档。

type RouterStd

type RouterStd struct {
	RouterCore      `alias:"routercore"`
	HandlerExtender `alias:"handlerextender"`
	Middlewares     *middlewareTree `alias:"middlewares"`
	GroupParams     Params          `alias:"params"`
	Logger          Logger          `alias:"logger"`
	LoggerKind      string          `alias:"loggerkind"`
	Meta            *MetadataRouter `alias:"meta"`
}

RouterStd default router registration implementation.

Need to specify a routing core, the default handler function extension is DefaultHandlerExtend. As a public attribute, it is only used by godoc to display the documentation of the relevant method.

RouterStd 默认路由器注册实现。

需要指定一个路由核心,处理函数扩展者默认为DefaultHandlerExtend。 作为公开属性仅用于godoc展示相关方法文档说明。

func (*RouterStd) AddController

func (r *RouterStd) AddController(controllers ...Controller) error

AddController method registers the controller, and the controller determines the routing registration behavior.

AddController 方法注册控制器,由控制器决定路由注册行为。

func (*RouterStd) AddHandler

func (r *RouterStd) AddHandler(method, path string, hs ...any) error

AddHandler method adds a new route, allowing multiple request methods to be added separately using','.

Nine methods defined by http can be registered (three of the Router interfaces do not provide direct registration), You can also register the method as: ANY TEST 404 405 NotFound MethodNotAllowed. If the registration method is ANY to register all methods, the ANY method route will be overwritten by the non-ANY method of the same path, and vice versa; if the registration method is TEST, it will output debug information related to route registration, but will not execute the registration behavior; The global variables DefaultRouterAnyMethod and DefaultRouterAllMethod set the Any registration method and the method that allows registration.

The handler parameter is processed using the HandlerExtender.NewHandlerFuncs() method of the current RouterStd to generate the corresponding HandlerFuncs.

If the current Router cannot be processed, call the HandlerExtender or defaultHandlerExtend of the upper-level group for processing, and output the error log if all of them cannot be processed.

The middleware data will be matched from the data according to the current routing path, and then the request processing function will be appended before the processing function.

AddHandler 方法添加一条新路由, 允许添加多个请求方法使用','分开。

可以注册http定义的9种方法(其中三种Router接口未提供直接注册), 也可以注册方法为:ANY TEST 404 405 NotFound MethodNotAllowed。 注册方法为ANY注册全部方法,ANY方法路由会被同路径非ANY方法覆盖,反之不行;注册方法为TEST会输出路由注册相关debug信息,但不执行注册行为; 全局变量DefaultRouterAnyMethod和DefaultRouterAllMethod设置Any注册方法和允许注册的方法。

handler参数使用当前RouterStd的HandlerExtender.NewHandlerFuncs()方法处理,生成对应的HandlerFuncs。

如果当前Router无法处理,则调用上一级group的HandlerExtender或defaultHandlerExtend处理,全部无法处理则输出error日志。

中间件数据会根据当前路由路径从数据中匹配,然后将请求处理函数附加到处理函数之前。

func (*RouterStd) AddHandlerExtend

func (r *RouterStd) AddHandlerExtend(handlers ...any) error

AddHandlerExtend method adds an extension function to the current Router.

If the number of parameters is greater than 1 and the first parameter is a string type, the first string type parameter is used as the path to add the extension function.

AddHandlerExtend 方法给当前Router添加扩展函数。

如果参数数量大于1且第一个参数为字符串类型,会将第一个字符串类型参数作为添加扩展函数的路径。

func (*RouterStd) AddMiddleware

func (r *RouterStd) AddMiddleware(hs ...any) error

AddMiddleware adds multiple middleware functions to the router, which will use HandlerExtender to convert parameters.

If the number of parameters is greater than 1 and the first parameter is a string type, the first string type parameter is used as the path to add the middleware.

AddMiddleware 给路由器添加多个中间件函数,会使用HandlerExtender转换参数。

如果参数数量大于1且第一个参数为字符串类型,会将第一个字符串类型参数作为添加中间件的路径。

func (*RouterStd) AnyFunc

func (r *RouterStd) AnyFunc(path string, h ...any)

AnyFunc method realizes the http request processing function that registers an Any method.

The routing rules registered by the Any method will be overwritten by the specified method registration, and vice versa. Any default registration method includes six types of Get Post Put Delete Head Patch, which are defined in the global variable RouterAnyMethod.

AnyFunc 方法实现注册一个Any方法的http请求处理函数。

Any方法注册的路由规则会被指定方法注册覆盖,反之不行。 Any默认注册方法包含Get Post Put Delete Head Patch六种,定义在全局变量RouterAnyMethod。

func (*RouterStd) DeleteFunc

func (r *RouterStd) DeleteFunc(path string, h ...any)

DeleteFunc 方法实现注册一个Delete方法的http请求处理函数。

func (*RouterStd) GetFunc

func (r *RouterStd) GetFunc(path string, h ...any)

GetFunc 方法实现注册一个Get方法的http请求处理函数。

func (*RouterStd) Group

func (r *RouterStd) Group(path string) Router

Group method returns a new group router.

The parameters, middleware, and function extensions of each Group group route registration will not affect the superior, but the subordinate will inherit the superior data.

The new Router will use the old RouterCore and Print objects; the middleware information and routing parameters are deep copied from the superior, while processing the Group parameters.

And create a new HandlerExtender in chain, if the type that HandlerExtender cannot register will call the previous Router.HandlerExtender to process.

The top-level HandlerExtender object is defaultHandlerExtend. You can use the RegisterHandlerExtend function and the NewHandlerFuncs function to call the defaultHandlerExtend object.

Group 方法返回一个新的组路由器。

每个Group组路由注册的参数、中间件、函数扩展都不会影响上级,但是下级会继承上级数据。

新的Router将使用旧的RouterCore和Print对象;中间件信息和路由参数从上级深拷贝一份,同时处理Group参数。

以及链式创建一个新的HandlerExtender,若HandlerExtender无法注册的类型将调用上一个Router.HandlerExtender处理。

最顶级HandlerExtender对象为defaultHandlerExtend, 可以使用RegisterHandlerExtend函数和NewHandlerFuncs函数调用defaultHandlerExtend对象。

func (*RouterStd) HeadFunc

func (r *RouterStd) HeadFunc(path string, h ...any)

HeadFunc 方法实现注册一个Head方法的http请求处理函数。

func (*RouterStd) Metadata

func (r *RouterStd) Metadata() any

Metadata 方法返回RouterCore的Metadata。

func (*RouterStd) Mount

func (r *RouterStd) Mount(ctx context.Context)

Mount 方法使RouterStd挂载上下文,上下文传递给RouterCore。

从ctx.Value(ContextKeyApp)获取Logger,初始化RouterStd日志输出函数。

从ctx.Value(ContextKeyHandlerExtender)获取HandlerExtender,替换DefaultHandlerExtender。

func (*RouterStd) Params

func (r *RouterStd) Params() *Params

Params method returns the current route parameters, and the route parameter value is an empty string will not be used.

Params 方法返回当前路由参数,路由参数值为空字符串不会被使用。

func (*RouterStd) PatchFunc

func (r *RouterStd) PatchFunc(path string, h ...any)

PatchFunc 方法实现注册一个Patch方法的http请求处理函数。

func (*RouterStd) PostFunc

func (r *RouterStd) PostFunc(path string, h ...any)

PostFunc 方法实现注册一个Post方法的http请求处理函数。

func (*RouterStd) PutFunc

func (r *RouterStd) PutFunc(path string, h ...any)

PutFunc 方法实现注册一个Put方法的http请求处理函数。

func (*RouterStd) Unmount

func (r *RouterStd) Unmount(ctx context.Context)

Unmount 方法使RouterStd卸载上下文,上下文传递给RouterCore。

type Server

type Server interface {
	SetHandler(http.Handler)
	Serve(net.Listener) error
	Shutdown(context.Context) error
}

Server 定义启动http服务的对象。

func NewServer

func NewServer(config *ServerConfig) Server

NewServer 创建一个标准server。

func NewServerFcgi

func NewServerFcgi() Server

NewServerFcgi 函数创建一个fcgi server。

type ServerConfig

type ServerConfig struct {
	// set default ServerHandler
	Handler http.Handler `alias:"handler" json:"-" xml:"-" yaml:"-"`

	// ReadTimeout is the maximum duration for reading the entire request, including the body.
	//
	// Because ReadTimeout does not let Handlers make per-request decisions on each request body's acceptable deadline or upload rate,
	// most users will prefer to use ReadHeaderTimeout. It is valid to use them both.
	ReadTimeout TimeDuration `alias:"readtimeout" json:"readtimeout" xml:"readtimeout" yaml:"readtimeout" description:"Http server read timeout."`

	// ReadHeaderTimeout is the amount of time allowed to read request headers.
	// The connection's read deadline is reset after reading the headers and the Handler can decide what is considered too slow for the body.
	ReadHeaderTimeout TimeDuration `` /* 146-byte string literal not displayed */
	// WriteTimeout is the maximum duration before timing out writes of the response.
	// It is reset whenever a new request's header is read.
	// Like ReadTimeout, it does not let Handlers make decisions on a per-request basis.
	WriteTimeout TimeDuration `alias:"writetimeout" json:"writetimeout" xml:"writetimeout" yaml:"writetimeout" description:"Http server write timeout."`

	// IdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled.
	// If IdleTimeout is zero, the value of ReadTimeout is used. If both are zero, ReadHeaderTimeout is used.
	IdleTimeout TimeDuration `alias:"idletimeout" json:"idletimeout" xml:"idletimeout" yaml:"idletimeout" description:"Http server idle timeout."`

	// MaxHeaderBytes controls the maximum number of bytes the server will read parsing the request header's keys and values, including the request line.
	// It does not limit the size of the request body. If zero, DefaultMaxHeaderBytes is used.
	MaxHeaderBytes int `` /* 130-byte string literal not displayed */

	// ErrorLog specifies an optional logger for errors accepting
	// connections, unexpected behavior from handlers, and
	// underlying FileSystem errors.
	// If nil, logging is done via the log package's standard logger.
	ErrorLog *log.Logger `alias:"errorlog" json:"-" xml:"-" yaml:"-"`

	// BaseContext optionally specifies a function that returns the base context for incoming requests on this server.
	// The provided Listener is the specific Listener that's about to start accepting requests.
	// If BaseContext is nil, the default is context.Background(). If non-nil, it must return a non-nil context.
	BaseContext func(net.Listener) context.Context `alias:"basecontext" json:"-" xml:"-" yaml:"-"`

	// ConnContext optionally specifies a function that modifies the context used for a new connection c.
	// The provided ctx is derived from the base context and has a ServerContextKey value.
	ConnContext func(context.Context, net.Conn) context.Context `alias:"conncontext" json:"-" xml:"-" yaml:"-"`
}

ServerConfig 定义serverStd使用的配置。

type ServerListenConfig

type ServerListenConfig struct {
	Addr        string            `alias:"addr" json:"addr" xml:"addr" yaml:"addr" description:"Listen addr."`
	HTTPS       bool              `alias:"https" json:"https" xml:"https" yaml:"https" description:"Is https."`
	HTTP2       bool              `alias:"http2" json:"http2" xml:"http2" yaml:"http2" description:"Is http2."`
	Mutual      bool              `alias:"mutual" json:"mutual" xml:"mutual" yaml:"mutual" description:"Is mutual tls."`
	Certfile    string            `alias:"certfile" json:"certfile" xml:"certfile" yaml:"certfile" description:"Http server cert file."`
	Keyfile     string            `alias:"keyfile" json:"keyfile" xml:"keyfile" yaml:"keyfile" description:"Http server key file."`
	Trustfile   string            `alias:"trustfile" json:"trustfile" xml:"trustfile" yaml:"trustfile" description:"Http client ca file."`
	Certificate *x509.Certificate `alias:"certificate" json:"certificate" xml:"certificate" yaml:"certificate" description:"https use tls certificate."`
}

ServerListenConfig 定义一个通用的端口监听配置,监听https仅支持单证书。

func (*ServerListenConfig) Listen

func (slc *ServerListenConfig) Listen() (net.Listener, error)

Listen 方法使ServerListenConfig实现serverListener接口,用于使用对象创建监听。

type TimeDuration

type TimeDuration time.Duration

TimeDuration 定义time.Duration类型处理json。

func (TimeDuration) MarshalText

func (d TimeDuration) MarshalText() ([]byte, error)

MarshalText 方法实现json序列化输出。

func (TimeDuration) String

func (d TimeDuration) String() string

String 方法格式化输出时间。

func (*TimeDuration) UnmarshalJSON

func (d *TimeDuration) UnmarshalJSON(b []byte) error

UnmarshalJSON 方法实现解析json格式时间。

func (*TimeDuration) UnmarshalText

func (d *TimeDuration) UnmarshalText(b []byte) error

UnmarshalText 方法实现解析时间。

type TypeNumber

type TypeNumber interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64 | complex64 | complex128
}

TypeNumber 定义泛型数值类型集合。

Directories

Path Synopsis
Package daemon 实现应用进程启动命令、后台启动、信号处理、热重启的代码支持。
Package daemon 实现应用进程启动命令、后台启动、信号处理、热重启的代码支持。
Package middleware 实现eudore基础请求中间件和处理函数。
Package middleware 实现eudore基础请求中间件和处理函数。

Jump to

Keyboard shortcuts

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