Documentation
¶
Index ¶
- Constants
- Variables
- func Contains[S ~[]E, E comparable](s S, v E) bool
- func ContainsAny(elems Array, v any) bool
- func D(f string, args ...any)
- func DBType(name ...string) string
- func DefaultErrorHandler(c Ctx, err error) error
- func Delete[S ~[]E, E any](s S, i, j int) S
- func Dir(root string, listDirectory bool) http.FileSystem
- func Dump(v ...any)
- func EnumFromString[T Enum](str string, mapping []string) T
- func EnumMarshalJSON[T Enum](val T, mapping []string) ([]byte, error)
- func EnumString[T Enum](val T, mapping []string) string
- func EnumUnmarshalJSON[T Enum](data []byte, mapping []string) (T, error)
- func EqualFold[S byteSeq](b, s S) bool
- func Erro(f string, args ...any)
- func Exists(absDir string) bool
- func Expr(expr string, args ...any) clause.Expr
- func Find(out any, args ...any) error
- func FixURI(pre, src, tag string) string
- func GetTrimmedParam(param string) string
- func Index[S ~[]E, E comparable](s S, v E) int
- func Info(f string, args ...any)
- func IsChild() bool
- func IsErrors(v any) bool
- func IsInvalidLengthError(err error) bool
- func LocalIP() (ip net.IP, err error)
- func Log(f string, args ...any)
- func MIME(extension string) (mime string)
- func MakePath(name, dst string, args ...any) (string, string, error)
- func NewModel(conf Options, debug, colorful bool) (map[string]*DB, error)
- func NewSnID() sid.ID
- func PrintJSON(v any, tags ...any)
- func RegHandle(mods ...any)
- func RegisterModule(inst module)
- func Remove[T comparable](elems []T, v T) []T
- func RemoveDuplicates[T comparable](slice []T) []T
- func RemoveEscapeChar(word string) string
- func RemoveEscapeCharBytes(word []byte) []byte
- func RoutePatternMatch(path, pattern string, cfg ...Options) bool
- func SaveConfigFile(conf map[string]any) error
- func StatusMessage(status int) string
- func ToAny[T any](items []T) []any
- func ToStrings[T fmt.Stringer](items []T) []string
- func ToStringsFromAny(items []any) []string
- func Warn(f string, args ...any)
- func WithTransaction(tx *DB, fn func(tx *DB) error) error
- type Array
- func (d Array) FindHandle(handle, value string) Map
- func (Array) GormDataType() string
- func (d Array) MarshalBinary() (data []byte, err error)
- func (d *Array) Scan(src any) error
- func (d Array) String() []string
- func (d Array) StringsJoin(sp string) string
- func (d *Array) UnmarshalBinary(data []byte) error
- func (d Array) Value() (driver.Value, error)
- type BaseCtx
- func (c *BaseCtx) Abort(args ...any) Ctx
- func (c *BaseCtx) Accepts(offers ...string) string
- func (c *BaseCtx) AcceptsCharsets(offers ...string) string
- func (c *BaseCtx) AcceptsEncodings(offers ...string) string
- func (c *BaseCtx) AcceptsLanguages(offers ...string) string
- func (c *BaseCtx) Append(key string, values ...string) Ctx
- func (c *BaseCtx) BodyParser(out any) error
- func (c *BaseCtx) Cookie(cookie *http.Cookie)
- func (c *BaseCtx) Cookies(name string) (string, error)
- func (c *BaseCtx) Core() *Core
- func (c *BaseCtx) File(filePath string)
- func (c *BaseCtx) FileAttachment(filepath, filename string)
- func (c *BaseCtx) FileFromFS(filepath string, fs http.FileSystem)
- func (c *BaseCtx) Flush(data any, statusCode ...int) error
- func (c *BaseCtx) FormFile(key string) (*multipart.FileHeader, error)
- func (c *BaseCtx) FormValue(key string, def ...string) string
- func (c *BaseCtx) FormValues(key string, def ...[]string) []string
- func (c *BaseCtx) Format(body any) error
- func (c *BaseCtx) FromValueInt(key string, def ...int) int
- func (c *BaseCtx) FromValueUUID(key string, def ...UUID) UUID
- func (c *BaseCtx) FromValueUid(key string, def ...uid.UID) uid.UID
- func (c *BaseCtx) Get(key string) (val any, ok bool)
- func (c *BaseCtx) GetAs(key string, v any) error
- func (c *BaseCtx) GetBool(key string) (value bool)
- func (c *BaseCtx) GetDuration(key string) (d time.Duration)
- func (c *BaseCtx) GetFloat64(key string, def ...float64) (value float64)
- func (c *BaseCtx) GetHeader(key string, defaultValue ...string) string
- func (c *BaseCtx) GetInt(key string, def ...int) (i int)
- func (c *BaseCtx) GetInt64(key string, def ...int64) (i int64)
- func (c *BaseCtx) GetMap(key string, def ...map[string]any) (value map[string]any)
- func (c *BaseCtx) GetMapString(key string, def ...map[string]string) (value map[string]string)
- func (c *BaseCtx) GetMapStringSlice(key string, def ...map[string][]string) (value map[string][]string)
- func (c *BaseCtx) GetParamInt(key string, defaultValue ...int) (int, error)
- func (c *BaseCtx) GetParamUid(key string, defaultValue ...uid.UID) (uid.UID, error)
- func (c *BaseCtx) GetStatus() int
- func (c *BaseCtx) GetString(key string, def ...string) (value string)
- func (c *BaseCtx) GetStrings(key string, def ...[]string) (value []string)
- func (c *BaseCtx) GetTime(key string) (t time.Time)
- func (c *BaseCtx) GetUUID(key string, def ...UUID) (v UUID)
- func (c *BaseCtx) GetUint(key string, def ...uint) (i uint)
- func (c *BaseCtx) GetUint64(key string, def ...uint64) (i uint64)
- func (c *BaseCtx) JSON(data any, code ...int) error
- func (c *BaseCtx) JSONP(data any, callback ...string) error
- func (c *BaseCtx) Method() string
- func (c *BaseCtx) Next() error
- func (c *BaseCtx) ParamUUID(key string, defaultValue ...UUID) UUID
- func (c *BaseCtx) Params(key string, defaultValue ...string) string
- func (c *BaseCtx) ParamsInt(key string, defaultValue ...int) (int, error)
- func (c *BaseCtx) ParamsUid(key string, defaultValue ...uid.UID) (uid.UID, error)
- func (c *BaseCtx) ParamsUuid(key string, defaultValue ...UUID) (UUID, error)
- func (c *BaseCtx) Path() string
- func (c *BaseCtx) Query(key string, def ...string) string
- func (c *BaseCtx) QueryInt(key string, def ...int) int
- func (c *BaseCtx) Querys(key string, def ...[]string) []string
- func (c *BaseCtx) ReadBody(out any, debug ...bool) error
- func (c *BaseCtx) Redirect(to string, stCode ...int)
- func (c *BaseCtx) RedirectJS(to string, msg ...string)
- func (c *BaseCtx) RemoteIP() net.IP
- func (c *BaseCtx) RemoveCookie(name, path string, dom ...string)
- func (c *BaseCtx) Render(f string, bind ...any) error
- func (c *BaseCtx) Request() *http.Request
- func (c *BaseCtx) Response() ResponseWriter
- func (c *BaseCtx) SaveFile(key, dst string, args ...any) (relpath, abspath string, err error)
- func (c *BaseCtx) SaveFiles(key, dst string, args ...any) (rel Array, err error)
- func (c *BaseCtx) Send(buf []byte) error
- func (c *BaseCtx) SendStatus(code int, msg ...string) error
- func (c *BaseCtx) SendString(str ...any) error
- func (c *BaseCtx) Set(key string, val any)
- func (c *BaseCtx) SetCookie(name, value string, exp time.Time, path string, args ...any)
- func (c *BaseCtx) SetHeader(key string, value string)
- func (c *BaseCtx) SetParams(key, val string)
- func (c *BaseCtx) StartAt(t ...time.Time) time.Time
- func (c *BaseCtx) Status(code int) Ctx
- func (c *BaseCtx) Stream(step func(w io.Writer) bool) bool
- func (c *BaseCtx) TextBytes(out io.Writer, f string, bind ...any) error
- func (c *BaseCtx) TextRender(f string, bind ...any) error
- func (c *BaseCtx) ToJSON(data any, msg ...any) error
- func (c *BaseCtx) ToJSONCode(data any, msg ...any) error
- func (c *BaseCtx) Type(extension string, charset ...string) Ctx
- func (c *BaseCtx) Validate(out any) error
- func (c *BaseCtx) Vars() Map
- func (c *BaseCtx) Vary(fields ...string) Ctx
- func (c *BaseCtx) ViewReload()
- func (c *BaseCtx) ViewTheme(theme string)
- func (c *BaseCtx) XML(data any) error
- type Constraint
- type Core
- func (app *Core) ALL(path string, handler any, middleware ...any) Router
- func (app *Core) AcquireCtx(w http.ResponseWriter, r *http.Request) Ctx
- func (app *Core) Add(methods []string, path string, handler any, middleware ...any) Router
- func (app *Core) AddHandle(methods []string, uri string, group *Group, handler any, ...) Router
- func (app *Core) CONNECT(path string, handler any, middleware ...any) Router
- func (app *Core) DELETE(path string, handler any, middleware ...any) Router
- func (app *Core) GET(path string, handler any, middleware ...any) Router
- func (app *Core) GetModule(id string) (ModuleInfo, error)
- func (app *Core) Group(prefix string, handlers ...HandlerFuncs) Router
- func (app *Core) HEAD(path string, handler any, middleware ...any) Router
- func (app *Core) Listen(port ...any) error
- func (app *Core) OPTIONS(path string, handler any, middleware ...any) Router
- func (app *Core) PATCH(path string, handler any, middleware ...any) Router
- func (app *Core) POST(path string, handler any, middleware ...any) Router
- func (app *Core) PUT(path string, handler any, middleware ...any) Router
- func (app *Core) ReleaseCtx(c Ctx)
- func (app *Core) Run(port ...any) error
- func (app *Core) Serve(ln net.Listener) error
- func (app *Core) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (app *Core) Static(relativePath, root string) Router
- func (app *Core) StaticFS(relativePath string, fs http.FileSystem) Router
- func (app *Core) StaticFile(relativePath, dirname string) Router
- func (app *Core) StaticFileFS(relativePath, dirname string, fs http.FileSystem) Router
- func (app *Core) TRACE(path string, handler any, middleware ...any) Router
- func (app *Core) Use(fn ...any) Router
- type Ctx
- type DB
- type Date
- type Enum
- type Error
- type ErrorHandler
- type Errors
- type EventData
- type EventHub
- type Group
- func (g *Group) ALL(path string, handler any, middleware ...any) Router
- func (g *Group) Add(methods []string, path string, handler any, middleware ...any) Router
- func (g *Group) CONNECT(path string, handler any, middleware ...any) Router
- func (g *Group) DELETE(path string, handler any, middleware ...any) Router
- func (g *Group) GET(path string, handler any, middleware ...any) Router
- func (g *Group) Group(prefix string, handlers ...any) *Group
- func (g *Group) HEAD(path string, handler any, middleware ...any) Router
- func (g *Group) Name(name string) Router
- func (g *Group) OPTIONS(path string, handler any, middleware ...any) Router
- func (g *Group) PATCH(path string, handler any, middleware ...any) Router
- func (g *Group) POST(path string, handler any, middleware ...any) Router
- func (g *Group) PUT(path string, handler any, middleware ...any) Router
- func (g *Group) TRACE(path string, handler any, middleware ...any) Router
- func (g *Group) Use(fn ...any) Router
- type Handler
- type HandlerFun
- type HandlerFunc
- type HandlerFuncs
- type HandlerNormal
- type HasUUID
- type HookWriter
- type Int
- type IntMoney
- func (m IntMoney) Abs() IntMoney
- func (m IntMoney) Add(x IntMoney) IntMoney
- func (m IntMoney) DivInt(n int64) IntMoney
- func (m IntMoney) EmvAmount() string
- func (m IntMoney) Float64() float64
- func (IntMoney) GormDBDataType(db *gorm.DB, field *schema.Field) string
- func (IntMoney) GormDataType() string
- func (m IntMoney) Int64() int64
- func (m IntMoney) IsEqual(x IntMoney, fraction ...int) bool
- func (m IntMoney) MarshalBinary() (data []byte, err error)
- func (m IntMoney) MarshalJSON() ([]byte, error)
- func (m IntMoney) MulInt(n int64) IntMoney
- func (m *IntMoney) Scan(value any) error
- func (m IntMoney) String() string
- func (m IntMoney) Sub(x IntMoney) IntMoney
- func (m IntMoney) ToFixed(fraction ...int) float64
- func (m *IntMoney) UnmarshalBinary(data []byte) error
- func (m *IntMoney) UnmarshalJSON(data []byte) error
- func (m IntMoney) Value() (driver.Value, error)
- type InvalidUnmarshalError
- type JSON
- func (JSON) GormDBDataType(db *gorm.DB, field *schema.Field) string
- func (JSON) GormDataType() string
- func (js JSON) GormValue(ctx context.Context, db *gorm.DB) clause.Expr
- func (j JSON) MarshalJSON() ([]byte, error)
- func (j *JSON) Scan(value interface{}) error
- func (j JSON) String() string
- func (j *JSON) UnmarshalJSON(b []byte) error
- func (j JSON) Value() (driver.Value, error)
- type LogMonitor
- type LoggerConfig
- type Map
- func (d Map) Contains(k string) bool
- func (d Map) GetAs(k string, v any) error
- func (d Map) GetBool(k string) (value bool)
- func (d Map) GetInt(k string, defaultValue ...int) (value int)
- func (d Map) GetString(k string, defaultValue ...string) (value string)
- func (Map) GormDataType() string
- func (d Map) MarshalBinary() (data []byte, err error)
- func (d *Map) Scan(src any) error
- func (d Map) ToString(k string, def ...string) string
- func (d *Map) UnmarshalBinary(data []byte) error
- func (d Map) UnmarshalTo(k string, v any) error
- func (d Map) Value() (driver.Value, error)
- type MethodType
- type Mod
- type Model
- type Models
- type Module
- type ModuleInfo
- type Money
- func (m Money) Abs() Money
- func (m Money) AddInt(in int, fraction ...int) Money
- func (m Money) DivInt(in int, fraction ...int) Money
- func (m Money) EmvAmount() string
- func (m Money) Float64() float64
- func (Money) GormDBDataType(db *gorm.DB, field *schema.Field) string
- func (m Money) Int() Int
- func (m Money) IsEqual(x Money, fixed ...int) bool
- func (m Money) MarshalBinary() (data []byte, err error)
- func (m Money) MarshalJSON() ([]byte, error)
- func (m Money) MulInt(in int, fraction ...int) Money
- func (m Money) SubInt(in int, fraction ...int) Money
- func (m Money) ToFixed(fraction ...int) Money
- func (m Money) ToFloor(p int) Money
- func (m Money) ToRound(p int) Money
- func (m *Money) UnmarshalBinary(data []byte) error
- func (m *Money) UnmarshalJSON(data []byte) error
- type NextPages
- type Options
- func (opt *Options) GetAs(k string, v any) error
- func (opt *Options) GetBool(k string, def ...bool) bool
- func (opt *Options) GetInt(k string, def ...int) int
- func (opt *Options) GetInt64(k string, def ...int64) int64
- func (opt *Options) GetMap(k string, def ...Options) Options
- func (opt *Options) GetString(k string, def ...string) string
- func (opt *Options) GetStrings(k string, def ...[]string) []string
- func (opt *Options) ToString(k string, def ...string) string
- func (opt *Options) Value(k string) (any, bool)
- type Pages
- type RecoveryFunc
- type ResponseWriter
- type RestfulDefine
- type RouteNode
- type Router
- type SModels
- type StringOrNil
- type TypeConstraint
- type UUID
- func (u UUID) Bytes() []byte
- func (UUID) GormDBDataType(db *gorm.DB, field *schema.Field) string
- func (uuid UUID) GormDataType() string
- func (u UUID) IsEmpty() bool
- func (u UUID) MarshalBinary() (data []byte, err error)
- func (id UUID) MarshalText() ([]byte, error)
- func (uuid *UUID) Scan(src any) error
- func (u UUID) String() string
- func (u *UUID) UnmarshalBinary(data []byte) error
- func (uuid *UUID) UnmarshalText(data []byte) error
- func (uuid UUID) Value() (driver.Value, error)
- type Writers
Constants ¶
const ( MIMETextXML = "text/xml" MIMETextHTML = "text/html" MIMETextPlain = "text/plain" MIMETextJavaScript = "text/javascript" MIMEApplicationXML = "application/xml" MIMEApplicationJSON = "application/json" // Deprecated: use MIMETextJavaScript instead MIMEApplicationJavaScript = "application/javascript" MIMEApplicationForm = "application/x-www-form-urlencoded" MIMEOctetStream = "application/octet-stream" MIMEMultipartForm = "multipart/form-data" MIMETextXMLCharsetUTF8 = "text/xml; charset=utf-8" MIMETextHTMLCharsetUTF8 = "text/html; charset=utf-8" MIMETextPlainCharsetUTF8 = "text/plain; charset=utf-8" MIMETextJavaScriptCharsetUTF8 = "text/javascript; charset=utf-8" MIMEApplicationXMLCharsetUTF8 = "application/xml; charset=utf-8" MIMEApplicationJSONCharsetUTF8 = "application/json; charset=utf-8" // Deprecated: use MIMETextJavaScriptCharsetUTF8 instead MIMEApplicationJavaScriptCharsetUTF8 = "application/javascript; charset=utf-8" )
MIME types that are commonly used
const ( CharsetUTF8 = "utf-8" CharsetGBK = "gbk" CharsetGB2312 = "gb2312" CharsetGB18030 = "gb18030" )
const ( StatusContinue = 100 // RFC 9110, 15.2.1 StatusSwitchingProtocols = 101 // RFC 9110, 15.2.2 StatusProcessing = 102 // RFC 2518, 10.1 StatusEarlyHints = 103 // RFC 8297 StatusOK = 200 // RFC 9110, 15.3.1 StatusCreated = 201 // RFC 9110, 15.3.2 StatusAccepted = 202 // RFC 9110, 15.3.3 StatusNonAuthoritativeInformation = 203 // RFC 9110, 15.3.4 StatusNoContent = 204 // RFC 9110, 15.3.5 StatusResetContent = 205 // RFC 9110, 15.3.6 StatusPartialContent = 206 // RFC 9110, 15.3.7 StatusMultiStatus = 207 // RFC 4918, 11.1 StatusAlreadyReported = 208 // RFC 5842, 7.1 StatusIMUsed = 226 // RFC 3229, 10.4.1 StatusMultipleChoices = 300 // RFC 9110, 15.4.1 StatusMovedPermanently = 301 // RFC 9110, 15.4.2 StatusFound = 302 // RFC 9110, 15.4.3 StatusSeeOther = 303 // RFC 9110, 15.4.4 StatusNotModified = 304 // RFC 9110, 15.4.5 StatusUseProxy = 305 // RFC 9110, 15.4.6 StatusSwitchProxy = 306 // RFC 9110, 15.4.7 (Unused) StatusTemporaryRedirect = 307 // RFC 9110, 15.4.8 StatusPermanentRedirect = 308 // RFC 9110, 15.4.9 StatusBadRequest = 400 // RFC 9110, 15.5.1 StatusPaymentRequired = 402 // RFC 9110, 15.5.3 StatusForbidden = 403 // RFC 9110, 15.5.4 StatusNotFound = 404 // RFC 9110, 15.5.5 StatusMethodNotAllowed = 405 // RFC 9110, 15.5.6 StatusNotAcceptable = 406 // RFC 9110, 15.5.7 StatusProxyAuthRequired = 407 // RFC 9110, 15.5.8 StatusRequestTimeout = 408 // RFC 9110, 15.5.9 StatusConflict = 409 // RFC 9110, 15.5.10 StatusGone = 410 // RFC 9110, 15.5.11 StatusLengthRequired = 411 // RFC 9110, 15.5.12 StatusPreconditionFailed = 412 // RFC 9110, 15.5.13 StatusRequestEntityTooLarge = 413 // RFC 9110, 15.5.14 StatusRequestURITooLong = 414 // RFC 9110, 15.5.15 StatusUnsupportedMediaType = 415 // RFC 9110, 15.5.16 StatusRequestedRangeNotSatisfiable = 416 // RFC 9110, 15.5.17 StatusExpectationFailed = 417 // RFC 9110, 15.5.18 StatusTeapot = 418 // RFC 9110, 15.5.19 (Unused) StatusMisdirectedRequest = 421 // RFC 9110, 15.5.20 StatusUnprocessableEntity = 422 // RFC 9110, 15.5.21 StatusLocked = 423 // RFC 4918, 11.3 StatusFailedDependency = 424 // RFC 4918, 11.4 StatusTooEarly = 425 // RFC 8470, 5.2. StatusUpgradeRequired = 426 // RFC 9110, 15.5.22 StatusPreconditionRequired = 428 // RFC 6585, 3 StatusTooManyRequests = 429 // RFC 6585, 4 StatusRequestHeaderFieldsTooLarge = 431 // RFC 6585, 5 StatusInternalServerError = 500 // RFC 9110, 15.6.1 StatusNotImplemented = 501 // RFC 9110, 15.6.2 StatusBadGateway = 502 // RFC 9110, 15.6.3 StatusGatewayTimeout = 504 // RFC 9110, 15.6.5 StatusHTTPVersionNotSupported = 505 // RFC 9110, 15.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 )
HTTP status codes were copied from https://github.com/nginx/nginx/blob/67d2a9541826ecd5db97d604f23460210fd3e517/conf/mime.types with the following updates: - Rename StatusNonAuthoritativeInfo to StatusNonAuthoritativeInformation - Add StatusSwitchProxy (306) NOTE: Keep this list in sync with statusMessage
const ( HeaderAuthorization = "Authorization" HeaderProxyAuthenticate = "Proxy-Authenticate" HeaderProxyAuthorization = "Proxy-Authorization" HeaderWWWAuthenticate = "WWW-Authenticate" HeaderAge = "Age" HeaderCacheControl = "Cache-Control" HeaderClearSiteData = "Clear-Site-Data" HeaderExpires = "Expires" HeaderPragma = "Pragma" HeaderWarning = "Warning" HeaderAcceptCH = "Accept-CH" HeaderAcceptCHLifetime = "Accept-CH-Lifetime" HeaderContentDPR = "Content-DPR" HeaderDPR = "DPR" HeaderEarlyData = "Early-Data" HeaderSaveData = "Save-Data" HeaderViewportWidth = "Viewport-Width" HeaderWidth = "Width" HeaderETag = "ETag" HeaderIfMatch = "If-Match" HeaderIfModifiedSince = "If-Modified-Since" HeaderIfNoneMatch = "If-None-Match" HeaderIfUnmodifiedSince = "If-Unmodified-Since" HeaderLastModified = "Last-Modified" HeaderVary = "Vary" HeaderConnection = "Connection" HeaderKeepAlive = "Keep-Alive" HeaderAccept = "Accept" HeaderAcceptCharset = "Accept-Charset" HeaderAcceptEncoding = "Accept-Encoding" HeaderAcceptLanguage = "Accept-Language" HeaderCookie = "Cookie" HeaderExpect = "Expect" HeaderMaxForwards = "Max-Forwards" HeaderSetCookie = "Set-Cookie" 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" HeaderOrigin = "Origin" HeaderTimingAllowOrigin = "Timing-Allow-Origin" HeaderXPermittedCrossDomainPolicies = "X-Permitted-Cross-Domain-Policies" HeaderDNT = "DNT" HeaderTk = "Tk" HeaderContentDisposition = "Content-Disposition" HeaderContentEncoding = "Content-Encoding" HeaderContentLanguage = "Content-Language" HeaderContentLength = "Content-Length" HeaderContentLocation = "Content-Location" HeaderContentType = "Content-Type" HeaderForwarded = "Forwarded" HeaderVia = "Via" HeaderXForwardedFor = "X-Forwarded-For" HeaderXForwardedHost = "X-Forwarded-Host" HeaderXForwardedProto = "X-Forwarded-Proto" HeaderXForwardedProtocol = "X-Forwarded-Protocol" HeaderXForwardedSsl = "X-Forwarded-Ssl" HeaderXUrlScheme = "X-Url-Scheme" HeaderLocation = "Location" HeaderFrom = "From" HeaderHost = "Host" HeaderReferer = "Referer" HeaderReferrerPolicy = "Referrer-Policy" HeaderUserAgent = "User-Agent" HeaderAllow = "Allow" HeaderServer = "Server" HeaderAcceptRanges = "Accept-Ranges" HeaderContentRange = "Content-Range" HeaderIfRange = "If-Range" HeaderRange = "Range" HeaderContentSecurityPolicy = "Content-Security-Policy" HeaderContentSecurityPolicyReportOnly = "Content-Security-Policy-Report-Only" HeaderCrossOriginResourcePolicy = "Cross-Origin-Resource-Policy" HeaderExpectCT = "Expect-CT" HeaderPermissionsPolicy = "Permissions-Policy" HeaderPublicKeyPins = "Public-Key-Pins" HeaderPublicKeyPinsReportOnly = "Public-Key-Pins-Report-Only" HeaderStrictTransportSecurity = "Strict-Transport-Security" HeaderUpgradeInsecureRequests = "Upgrade-Insecure-Requests" HeaderXContentTypeOptions = "X-Content-Type-Options" HeaderXDownloadOptions = "X-Download-Options" HeaderXFrameOptions = "X-Frame-Options" HeaderXPoweredBy = "X-Powered-By" HeaderXXSSProtection = "X-XSS-Protection" HeaderLastEventID = "Last-Event-ID" HeaderNEL = "NEL" HeaderPingFrom = "Ping-From" HeaderPingTo = "Ping-To" HeaderReportTo = "Report-To" HeaderTE = "TE" HeaderTrailer = "Trailer" HeaderTransferEncoding = "Transfer-Encoding" HeaderSecWebSocketAccept = "Sec-WebSocket-Accept" HeaderSecWebSocketExtensions = "Sec-WebSocket-Extensions" HeaderSecWebSocketKey = "Sec-WebSocket-Key" HeaderSecWebSocketProtocol = "Sec-WebSocket-Protocol" HeaderSecWebSocketVersion = "Sec-WebSocket-Version" HeaderAcceptPatch = "Accept-Patch" HeaderAcceptPushPolicy = "Accept-Push-Policy" HeaderAcceptSignature = "Accept-Signature" HeaderAltSvc = "Alt-Svc" HeaderDate = "Date" HeaderIndex = "Index" HeaderLargeAllocation = "Large-Allocation" HeaderLink = "Link" HeaderPushPolicy = "Push-Policy" HeaderRetryAfter = "Retry-After" HeaderServerTiming = "Server-Timing" HeaderSignature = "Signature" HeaderSignedHeaders = "Signed-Headers" HeaderSourceMap = "SourceMap" HeaderUpgrade = "Upgrade" HeaderXDNSPrefetchControl = "X-DNS-Prefetch-Control" HeaderXPingback = "X-Pingback" HeaderXRequestID = "X-Request-ID" HeaderXRequestedWith = "X-Requested-With" HeaderXRobotsTag = "X-Robots-Tag" HeaderXUACompatible = "X-UA-Compatible" )
HTTP Headers were copied from net/http.
const ( DefaultDateFormat = "2006-01-02" DefaultDateTimeFormat = "2006-01-02 15:04" )
const ( ConstraintInt = "int" ConstraintBool = "bool" ConstraintFloat = "float" ConstraintAlpha = "alpha" ConstraintGUID = "guid" ConstraintMinLen = "minLen" ConstraintMaxLen = "maxLen" ConstraintLen = "len" ConstraintBetweenLen = "betweenLen" ConstraintMinLenLower = "minlen" ConstraintMaxLenLower = "maxlen" ConstraintBetweenLenLower = "betweenlen" ConstraintMin = "min" ConstraintMax = "max" ConstraintRange = "range" ConstraintDatetime = "datetime" ConstraintRegex = "regex" )
Route Constraints
const CoreHeader = `` /* 185-byte string literal not displayed */
const VERSION = "v3.0.0"
Variables ¶
var ( MethodUse = Methods[METHOD_USE] MethodGet = Methods[METHOD_GET] MethodPost = Methods[METHOD_POST] MethodHead = Methods[METHOD_HEAD] MethodPut = Methods[METHOD_PUT] MethodDelete = Methods[METHOD_DELETE] MethodOptions = Methods[METHOD_OPTIONS] MethodConnect = Methods[METHOD_CONNECT] MethodTrace = Methods[METHOD_TRACE] MethodPatch = Methods[METHOD_PATCH] )
var ( ErrDataTypeNotSupport = errors.New("dataType does not support") ErrNoConfig = errors.New("field global configuration not found") ErrLayoutCalledUnexpectedly = errors.New("layout called unexpectedly") )
var ( ErrBadRequest = NewError(StatusBadRequest) // 400 ErrPaymentRequired = NewError(StatusPaymentRequired) // 402 ErrForbidden = NewError(StatusForbidden) // 403 ErrNotFound = NewError(StatusNotFound) // 404 ErrMethodNotAllowed = NewError(StatusMethodNotAllowed) // 405 ErrNotAcceptable = NewError(StatusNotAcceptable) // 406 ErrProxyAuthRequired = NewError(StatusProxyAuthRequired) // 407 ErrRequestTimeout = NewError(StatusRequestTimeout) // 408 ErrConflict = NewError(StatusConflict) // 409 ErrGone = NewError(StatusGone) // 410 ErrLengthRequired = NewError(StatusLengthRequired) // 411 ErrPreconditionFailed = NewError(StatusPreconditionFailed) // 412 ErrRequestEntityTooLarge = NewError(StatusRequestEntityTooLarge) // 413 ErrRequestURITooLong = NewError(StatusRequestURITooLong) // 414 ErrUnsupportedMediaType = NewError(StatusUnsupportedMediaType) // 415 ErrRequestedRangeNotSatisfiable = NewError(StatusRequestedRangeNotSatisfiable) // 416 ErrExpectationFailed = NewError(StatusExpectationFailed) // 417 ErrTeapot = NewError(StatusTeapot) // 418 ErrMisdirectedRequest = NewError(StatusMisdirectedRequest) // 421 ErrUnprocessableEntity = NewError(StatusUnprocessableEntity) // 422 ErrLocked = NewError(StatusLocked) // 423 ErrFailedDependency = NewError(StatusFailedDependency) // 424 ErrTooEarly = NewError(StatusTooEarly) // 425 ErrUpgradeRequired = NewError(StatusUpgradeRequired) // 426 ErrPreconditionRequired = NewError(StatusPreconditionRequired) // 428 ErrTooManyRequests = NewError(StatusTooManyRequests) // 429 ErrRequestHeaderFieldsTooLarge = NewError(StatusRequestHeaderFieldsTooLarge) // 431 ErrInternalServerError = NewError(StatusInternalServerError) // 500 ErrNotImplemented = NewError(StatusNotImplemented) // 501 ErrBadGateway = NewError(StatusBadGateway) // 502 ErrGatewayTimeout = NewError(StatusGatewayTimeout) // 504 ErrHTTPVersionNotSupported = NewError(StatusHTTPVersionNotSupported) // 505 ErrVariantAlsoNegotiates = NewError(StatusVariantAlsoNegotiates) // 506 ErrInsufficientStorage = NewError(StatusInsufficientStorage) // 507 ErrLoopDetected = NewError(StatusLoopDetected) // 508 ErrNotExtended = NewError(StatusNotExtended) // 510 ErrNetworkAuthenticationRequired = NewError(StatusNetworkAuthenticationRequired) // 511 )
Errors
var ( DefaultErrorWriter io.Writer = os.Stderr LogHub = NewLogMonitor() )
DefaultErrorWriter is the default io.Writer used by Gin to debug errors
var (
DefaultOutput = io.Discard
)
var (
ErrInvalidValidationType = NewError(400, "验证类型必须是结构体指针")
)
全局验证器实例 自定义错误类型
var (
Methods = []string{
"GET",
"POST",
"HEAD",
"PUT",
"DELETE",
"OPTIONS",
"CONNECT",
"TRACE",
"PATCH",
"USE",
}
)
var (
SnID *sid.SnowflakeID
)
var UuidNil = UUID{uuid.Nil}
Functions ¶
func Contains ¶
func Contains[S ~[]E, E comparable](s S, v E) bool
func ContainsAny ¶
func DefaultErrorHandler ¶
func Delete ¶
Delete removes the elements s[i:j] from s, returning the modified slice. Delete panics if s[i:j] is not a valid slice of s. Delete is O(len(s)-j), so if many items must be deleted, it is better to make a single call deleting them all together than to delete one at a time. Delete might not modify the elements s[len(s)-(j-i):len(s)]. If those elements contain pointers you might consider zeroing those elements so that objects they reference can be garbage collected.
func Dir ¶
func Dir(root string, listDirectory bool) http.FileSystem
Dir returns a http.FileSystem that can be used by http.FileServer(). It is used internally in router.Static(). if listDirectory == true, then it works the same as http.Dir() otherwise it returns a filesystem that prevents http.FileServer() to list the directory files.
func EnumFromString ¶
EnumFromString
func TypeXFromString(str string) TypeX {
return EnumFromString[TypeX](str, TypeXMap)
}
func EnumMarshalJSON ¶
EnumMarshalJSON
func (s TypeX)MarshalJSON() ([]byte, error) {
return EnumMarshalJSON(s, TypeX)
}
func EnumUnmarshalJSON ¶
EnumUnmarshalJSON
func (s *TypeX) UnmarshalJSON(data []byte) error {
val, err := EnumUnmarshalJSON[TypeX](data, TypeXMap)
if err != nil {
return err
}
*s = val
return nil
}
func EqualFold ¶
func EqualFold[S byteSeq](b, s S) bool
EqualFold tests ascii strings or bytes for equality case-insensitively
func GetTrimmedParam ¶
GetTrimmedParam trims the ':' & '?' from a string
func Index ¶
func Index[S ~[]E, E comparable](s S, v E) int
func IsInvalidLengthError ¶
IsInvalidLengthError is matcher function for custom error invalidLengthError
func MakePath ¶
MakePath make dir
path = {root}/{dst}/{id}
@param
name string filename
dst string dst path
root string root path optional
id path optional type uid.UID, int, uint, int64,uint64
rename bool optional
return relPath, absPath
`
MakePath("favicon.png", "/images")
(string) relpath "/images/10/favicon.png"
(string) abspath "/images/10/favicon.png"
MakePath("favicon.png", "/images", "/static")
(string) relpath "/images/10/5hsbkthaadld/favicon.png"
(string) abspath "/static/images/10/5hsbkthaadld/favicon.png"
MakePath("favicon.png", "/images", "/static", uid.New())
(string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
(string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"
👇filename 👇dst 👇root 👇id 👇rename
MakePath("favicon.png", "/images", "/static", uid.New(), true)
(string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
(string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"
`
func RegisterModule ¶
func RegisterModule(inst module)
func RemoveDuplicates ¶
func RemoveDuplicates[T comparable](slice []T) []T
RemoveDuplicates 去重函数,适用于任何类型的切片
func RemoveEscapeChar ¶
RemoveEscapeChar removes escape characters
func RemoveEscapeCharBytes ¶
RemoveEscapeCharBytes removes escape characters
func RoutePatternMatch ¶
RoutePatternMatch checks if a given path matches a core route pattern.
func SaveConfigFile ¶
func StatusMessage ¶
StatusMessage returns the correct message for the provided HTTP statuscode
func ToStringsFromAny ¶
ToStringsFromAny 把 []any 转换成 []string
Types ¶
type Array ¶
type Array []any
Array 数组类型
func ParseAndDeduplicate ¶
ParseAndDeduplicate 将输入字符串按逗号分割,去除空字段及重复值
func (Array) FindHandle ¶
func (Array) MarshalBinary ¶
func (*Array) UnmarshalBinary ¶
type BaseCtx ¶
type BaseCtx struct {
W ResponseWriter
R *http.Request
// contains filtered or unexported fields
}
func (*BaseCtx) Accepts ¶
Accepts checks if the specified extensions or content types are acceptable.
func (*BaseCtx) AcceptsCharsets ¶
AcceptsCharsets checks if the specified charset is acceptable.
func (*BaseCtx) AcceptsEncodings ¶
AcceptsEncodings checks if the specified encoding is acceptable.
func (*BaseCtx) AcceptsLanguages ¶
AcceptsLanguages checks if the specified language is acceptable.
func (*BaseCtx) Append ¶
Append values to the same key, separated by commas
c.Append("Vary", "Accept-Encoding", "Accept", "X-Requested-With")
Response Header:
Vary: Accept-Encoding, Accept, X-Requested-With
func (*BaseCtx) BodyParser ¶
BodyParser parses the request body into the provided 'out' parameter. It delegates the actual parsing to the ReadBody method.
func (*BaseCtx) Cookies ¶
Cookie returns the named cookie provided in the request or ErrNoCookie if not found. And return the named cookie is unescaped. If multiple cookies match the given name, only one cookie will be returned.
func (*BaseCtx) FileAttachment ¶
FileAttachment writes the specified file into the body stream in an efficient way On the client side, the file will typically be downloaded with the given filename
func (*BaseCtx) FileFromFS ¶
func (c *BaseCtx) FileFromFS(filepath string, fs http.FileSystem)
FileFromFS writes the specified file from http.FileSystem into the body stream in an efficient way.
func (*BaseCtx) FormFile ¶
func (c *BaseCtx) FormFile(key string) (*multipart.FileHeader, error)
FormFile returns the first file for the provided form key. FormFile calls ParseMultipartForm and ParseForm if necessary.
func (*BaseCtx) FormValues ¶
FormValues returns a slice of strings for a given query key.
func (*BaseCtx) Format ¶
Format performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format. If the header is not specified or there is no proper format, text/plain is used.
func (*BaseCtx) Get ¶
Get returns the value for the given key, ie: (value, true). If the value does not exists it returns (nil, false)
func (*BaseCtx) GetAs ¶
GetAs retrieve struct like c.Get("user").(User)
> Experimental function, problem unknown
func (*BaseCtx) GetDuration ¶
GetDuration returns the value associated with the key as a duration.
func (*BaseCtx) GetFloat64 ¶
GetFloat64 returns the value associated with the key as a float64.
func (*BaseCtx) GetMap ¶
GetMap returns the value associated with the key as a map of interfaces.
> return map[string]any
func (*BaseCtx) GetMapString ¶
GetMapString returns the value associated with the key as a map of strings.
> return map[string]string
func (*BaseCtx) GetMapStringSlice ¶
func (c *BaseCtx) GetMapStringSlice(key string, def ...map[string][]string) (value map[string][]string)
GetStringMapStringSlice returns the value associated with the key as a map to a slice of strings.
> return map[string][]string
func (*BaseCtx) GetParamInt ¶
GetParamInt get int param, return -1 if failed
func (*BaseCtx) GetParamUid ¶
GetParamUid get uid.UID param, return uid.Nil if failed
func (*BaseCtx) GetStrings ¶
GetStrings String Slice returns the value associated with the key as a slice of strings.
func (*BaseCtx) ParamsUuid ¶
ParamsUid get uid.UID param, return uid.Nil if failed
func (*BaseCtx) Query ¶
FormValue Get query
key string def string default val optional
> GET /?name=Jack&id=
`
name := c.FormValue("name") // name = Jack
id := c.FormValue("id", "1") // id = 1 Because the default value is used
`
func (*BaseCtx) ReadBody ¶
ReadBody binds the request body to a struct. It supports decoding the following content types based on the Content-Type header: application/json, application/xml, application/x-www-form-urlencoded, multipart/form-data If none of the content types above are matched, it will return a ErrUnprocessableEntity error
out any MIMEApplicationForm MIMEMultipartForm MIMETextXML must struct
func (*BaseCtx) RedirectJS ¶
func (*BaseCtx) RemoteIP ¶
RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port). It also checks if the remoteIP is a trusted proxy or not. In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
func (*BaseCtx) RemoveCookie ¶
func (*BaseCtx) Response ¶
func (c *BaseCtx) Response() ResponseWriter
ResponseWriter implements Ctx.
func (*BaseCtx) SaveFile ¶
SaveFile upload file save to a folder
path = {root}/{dst}/{id}
@param
name string filename
dst string dst path
root string root path optional
id path optional type uid.UID, int, uint, int64,uint64
rename bool optional
return relPath, absPath
c.SaveFile("file", "/images")
(string) relpath "/images/10/favicon.png"
(string) abspath "/images/10/favicon.png"
c.SaveFile("file", "/images", "./static")
(string) relpath "/images/10/5hsbkthaadld/favicon.png"
(string) abspath "/static/images/10/5hsbkthaadld/favicon.png"
c.SaveFile("file", "/images", "./static", uid.New())
(string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
(string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"
👇file 👇dst 👇root 👇id 👇rename
c.SaveFile("file", "/images", "./static", uid.New(), true)
(string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
(string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"
func (*BaseCtx) SaveFiles ¶
SaveFiles like SaveFile
@params key string MultipartForm key name : files dst string static to ./static more args see SaveFile
rel, err := c.SaveFiles("files", "static", true)
return relative url path rel is
return []string {
"/static/09/wjejwifx.jpg",
"/static/09/wjejwifx.jpg",
"/static/09/wjejwifx.jpg",
}
func (*BaseCtx) SendString ¶
func (*BaseCtx) SetCookie ¶
SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
func (*BaseCtx) Stream ¶
Stream sends a streaming response and returns a boolean indicates "Is client disconnected in middle of stream"
func (*BaseCtx) Type ¶
Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
func (*BaseCtx) Vary ¶
Vary add the given header field to the vary response header
c.Vary("Accept-Encoding", "Accept", "X-Requested-With")
Response Header:
Vary: Accept-Encoding, Accept, X-Requested-With
func (*BaseCtx) ViewReload ¶
func (c *BaseCtx) ViewReload()
type Constraint ¶
type Constraint struct {
ID TypeConstraint
RegexCompiler *regexp.Regexp
Data []string
}
func (*Constraint) CheckConstraint ¶
func (c *Constraint) CheckConstraint(param string) bool
type Core ¶
type Core struct {
*http.Server
Conf Options
Debug bool
RequestMethods []string
ErrorHandler ErrorHandler
Ctx context.Context
MaxMultipartMemory int64
Views view.IEngine
TextEngine view.ITextEngine
// contains filtered or unexported fields
}
func (*Core) AcquireCtx ¶
func (*Core) ReleaseCtx ¶
func (*Core) StaticFileFS ¶
func (app *Core) StaticFileFS(relativePath, dirname string, fs http.FileSystem) Router
StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead..
app.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false})
type Ctx ¶
type Ctx interface {
Response() ResponseWriter // Response() return http.ResponseWriter
Request() *http.Request // Request() return *http.Request
RedirectJS(to string, msg ...string) // use js redirect
Redirect(to string, stCode ...int) // base redirect
RemoteIP() net.IP // remote client ip
SetCookie(name, value string, exp time.Time, path string, args ...any) // set cookie
RemoveCookie(name, path string, dom ...string) // remove some cookie
Cookie(cookie *http.Cookie) // set cookie with cookie object
Cookies(name string) (string, error) // get some cookie
ReadBody(out any, debug ...bool) error // read put post any request body to struct or map
BodyParser(out any) error // read put post form data to struct or map
Validate(out any) error // validate struct or map
Next() error // next HandlerFunc
Path() string // return http.Request.URI.path
Send(buf []byte) error // send []byte data
SendString(msg ...any) error // send string to body
SendStatus(code int, msg ...string) error // send status to client, options msg with display
SetHeader(key string, value string) // set response header
GetHeader(key string, defaultValue ...string) string // get request header
Method() string // return method e.g: GET,POST,PUT,DELETE,OPTION,HEAD...
GetStatus() int // get response status
Status(code int) Ctx // set response status
Core() *Core // return app(*Core)
Abort(args ...any) Ctx // Deprecated: As of v2.0.0, this function simply calls Ctx.Format.
JSON(any, ...int) error // send json
JSONP(data any, callback ...string) error // send jsonp
ToJSON(data any, msg ...any) error // send json with status
ToJSONCode(data any, msg ...any) error // send have code to json
StartAt(t ...time.Time) time.Time // set ctx start time if t set, else get start at
Params(key string, defaultValue ...string) string // get Param data e.g c.Param("param")
ParamsUid(key string, defaultValue ...uid.UID) (uid.UID, error) // get Param UID type, return uid.Nil if failed
ParamsUuid(key string, defaultValue ...UUID) (UUID, error) // get Param UID type, return uid.Nil if failed
ParamUUID(key string, defaultValue ...UUID) UUID // get Param UUID type, return uid.Nil if failed
ParamsInt(key string, defaultValue ...int) (int, error) // get Param int type, return -1 if failed
GetParamUid(key string, defaultValue ...uid.UID) (uid.UID, error) // get param uid.UID, return uid.Nil if failed
GetParamInt(key string, defaultValue ...int) (int, error) // get param int, return -1 if failed
File(filePath string) // send file
FileAttachment(filepath, filename string) // send file attachment
FileFromFS(filePath string, fs http.FileSystem) // send file from FS
Append(key string, values ...string) Ctx // append response header
Vary(fields ...string) Ctx // set response vary
SaveFile(key, dst string, args ...any) (relpath, abspath string, err error) // upload some one file
SaveFiles(key, dst string, args ...any) (rel Array, err error) // upload multi-file
Query(key string, def ...string) string // get request query string like ?id=12345
QueryInt(key string, def ...int) int // parse form value to int
Querys(key string, def ...[]string) []string // like query, but return []string values
FormValue(key string, def ...string) string // like Query support old version
FromValueInt(key string, def ...int) int // parse form value to int
FromValueUid(key string, def ...uid.UID) uid.UID // parse form value to uid
FromValueUUID(key string, def ...UUID) UUID // parse form value to uuid
FormValues(key string, def ...[]string) []string // like Querys
Flush(data any, statusCode ...int) error // flush
Accepts(offers ...string) string // Accepts checks if the specified extensions or content types are acceptable.
AcceptsCharsets(offers ...string) string // AcceptsCharsets checks if the specified charset is acceptable.
AcceptsEncodings(offers ...string) string // AcceptsEncodings checks if the specified encoding is acceptable.
AcceptsLanguages(offers ...string) string // AcceptsLanguages checks if the specified language is acceptable.
Format(body any) error // Format performs content-negotiation on the Accept HTTP header. It uses Accepts to select a proper format. If the header is not specified or there is no proper format, text/plain is used.
Type(extension string, charset ...string) Ctx // 发送 response content-type
XML(data any) error // output xml
Set(key string, val any)
Get(key string) (val any, ok bool)
GetString(key string, def ...string) (value string)
GetBool(key string) (value bool)
GetInt(key string, def ...int) (i int)
GetInt64(key string, def ...int64) (i int64)
GetUint(key string, def ...uint) (i uint)
GetUint64(key string, def ...uint64) (i uint64)
GetUUID(key string, def ...UUID) (v UUID)
GetFloat64(key string, def ...float64) (value float64)
GetTime(key string) (t time.Time)
GetDuration(key string) (d time.Duration)
GetStrings(key string, def ...[]string) (value []string)
GetMap(key string, def ...map[string]any) (value map[string]any)
GetMapString(key string, def ...map[string]string) (value map[string]string)
GetMapStringSlice(key string, def ...map[string][]string) (value map[string][]string)
GetAs(key string, v any) error
Vars() Map
Stream(step func(w io.Writer) bool) bool
ViewReload() // set view reload
Render(f string, bind ...any) error
TextBytes(out io.Writer, f string, bind ...any) error
TextRender(f string, bind ...any) error
SetParams(key string, val string)
// contains filtered or unexported methods
}
type Error ¶
Error represents an error that occurred while handling a request.
type ErrorHandler ¶
type EventHub ¶
type EventHub struct {
// contains filtered or unexported fields
}
func NewEventHub ¶
func (*EventHub) UnRegister ¶
type Group ¶
func (*Group) GET ¶
Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.
func (*Group) Use ¶
Use registers a middleware route that will match requests with the provided prefix (which is optional and defaults to "/"). Also, you can pass another app instance as a sub-router along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Use. The core error handler and any of the core sub apps are added to the application's error handlers to be invoked on errors that happen within the prefix route.
app.Use(func(c core.Ctx) error {
return c.Next()
})
app.Use("/api", func(c core.Ctx) error {
return c.Next()
})
app.Use("/api", handler, func(c core.Ctx) error {
return c.Next()
})
subApp := core.New()
app.Use("/mounted-path", subApp)
This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...
type Handler ¶
type Handler struct {
Handlers map[string]any // record callable handle
ID string
// contains filtered or unexported fields
}
func (*Handler) PushHandler ¶
type HandlerFun ¶
type HandlerFun = func(Ctx)
type HandlerFunc ¶
func CustomRecoveryWithWriter ¶
func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc
CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.
func Logger ¶
func Logger(conf ...LoggerConfig) HandlerFunc
func Recovery ¶
func Recovery() HandlerFunc
Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
func RecoveryWithWriter ¶
func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc
RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
type HandlerFuncs ¶
type HandlerFuncs []HandlerFunc
type HandlerNormal ¶
type HandlerNormal = func(w http.ResponseWriter, r *http.Request)
type HookWriter ¶
type HookWriter struct {
Writer io.Writer
Monitor *LogMonitor
}
type IntMoney ¶
type IntMoney int64
func IntMoneyFromRedisString ¶
Scan 实现 sql.Scanner (数据库读取时转为 IntMoney) 不做 100 倍转换
func NewIntMoneyFromFloat ¶
NewIntMoneyFromFloat 创建 IntMoney(内部存储分)
func (IntMoney) GormDBDataType ¶
GormDBDataType gorm 方言映射 (不同数据库可指定不同字段类型)
func (IntMoney) GormDataType ¶
GormDataType gorm 通用数据类型 (用于生成表结构)
func (IntMoney) MarshalBinary ¶
func (*IntMoney) UnmarshalBinary ¶
func (*IntMoney) UnmarshalJSON ¶
UnmarshalJSON 反序列化
type InvalidUnmarshalError ¶
An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. (The argument to Unmarshal must be a non-nil pointer.)
func (*InvalidUnmarshalError) Error ¶
func (e *InvalidUnmarshalError) Error() string
type JSON ¶
type JSON json.RawMessage
func (JSON) MarshalJSON ¶
MarshalJSON to output non base64 encoded []byte
func (*JSON) UnmarshalJSON ¶
UnmarshalJSON to deserialize []byte
type LogMonitor ¶
type LogMonitor struct {
// contains filtered or unexported fields
}
func NewLogMonitor ¶
func NewLogMonitor() *LogMonitor
func (*LogMonitor) Broadcast ¶
func (m *LogMonitor) Broadcast(msg string)
func (*LogMonitor) Register ¶
func (m *LogMonitor) Register(c chan string)
func (*LogMonitor) UnRegister ¶
func (m *LogMonitor) UnRegister(c chan string)
type LoggerConfig ¶
type MethodType ¶
type MethodType uint8
const ( METHOD_GET MethodType = iota METHOD_POST METHOD_HEAD METHOD_PUT METHOD_DELETE METHOD_OPTIONS METHOD_CONNECT METHOD_TRACE METHOD_PATCH METHOD_USE )
type Model ¶
type Model struct {
ID uid.UID `gorm:"size:12;primaryKey" json:"id,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty" gorm:"<-:create"`
UpdatedAt time.Time `json:"updated_at,omitempty" gorm:"autoUpdateTime"`
DeletedAt *gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index"`
}
func (*Model) BeforeCreate ¶
type Models ¶
type Models struct {
ID UUID `json:"id,omitzero" gorm:"size:32;primaryKey"`
CreatedAt *time.Time `json:"created_at,omitempty" gorm:"<-:create"`
UpdatedAt *time.Time `json:"updated_at,omitempty" gorm:"autoUpdateTime"`
DeletedAt *gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index"`
}
func (*Models) BeforeCreate ¶
type ModuleInfo ¶
type Money ¶
type Money float64
func ParseMoney ¶
func (Money) GormDBDataType ¶
GormDBDataType gorm 方言映射 (不同数据库可指定不同字段类型)
func (Money) MarshalBinary ¶ added in v3.0.1
func (Money) MarshalJSON ¶
func (Money) ToFixed ¶
ToFixed 保留几位小数 Param fraction int return float64
func (m Money) ToFixed(fraction ...int) Money {
places := 2
if len(fraction) > 0 {
places = fraction[0]
}
shift := math.Pow(10, float64(places))
fv := 0.0000000001 + float64(m) //对浮点数产生.xxx999999999 计算不准进行处理
return Money(math.Floor(fv*shift) / shift)
}
func (*Money) UnmarshalBinary ¶ added in v3.0.1
func (*Money) UnmarshalJSON ¶
type NextPages ¶
type Pages ¶
type RecoveryFunc ¶
RecoveryFunc defines the function passable to CustomRecovery.
type ResponseWriter ¶
type ResponseWriter interface {
http.ResponseWriter
http.Hijacker
http.Flusher
// Returns the HTTP response status code of the current request.
Status() int
// Returns the number of bytes already written into the response http body.
// See Written()
Size() int
// Writes the string into the response body.
WriteString(string) (int, error)
// Returns true if the response body was already written.
Written() bool
// Forces to write the http header (status code + headers).
DoWriteHeader()
// get the http.Pusher for server push
Pusher() http.Pusher
}
ResponseWriter ...
type RestfulDefine ¶
type Router ¶
type Router interface {
Use(args ...any) Router
GET(path string, handler any, middleware ...any) Router
HEAD(path string, handler any, middleware ...any) Router
POST(path string, handler any, middleware ...any) Router
PUT(path string, handler any, middleware ...any) Router
DELETE(path string, handler any, middleware ...any) Router
CONNECT(path string, handler any, middleware ...any) Router
OPTIONS(path string, handler any, middleware ...any) Router
TRACE(path string, handler any, middleware ...any) Router
PATCH(path string, handler any, middleware ...any) Router
ALL(path string, handler any, middleware ...any) Router
// contains filtered or unexported methods
}
Router defines all router handle interface, including app and group router.
type SModels ¶ added in v3.0.3
type SModels struct {
ID sid.ID `json:"id,omitzero" gorm:"primaryKey;comment:主键"`
CreatedAt *time.Time `json:"created_at,omitempty" gorm:"<-:create;comment:创建时间"`
UpdatedAt *time.Time `json:"updated_at,omitempty" gorm:"autoUpdateTime;comment:更新时间"`
DeletedAt *gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index;comment:删除时间"`
}
func (*SModels) BeforeCreate ¶ added in v3.0.3
type StringOrNil ¶
type StringOrNil string
空字符串 存入数据库 存 NULL ,这样会跳过数据库唯一索引的检查
func (*StringOrNil) Scan ¶
func (s *StringOrNil) Scan(src any) error
implements sql.Scanner, will be invoked automatically when read from the db
func (StringOrNil) String ¶
func (s StringOrNil) String() string
type UUID ¶
func ExtractUUIDs ¶
func ParseBytes ¶
ParseBytes is like Parse, except it parses a byte slice instead of a string.
func UUIDFromString ¶
func (UUID) GormDataType ¶
GormDataType gorm common data type
func (UUID) MarshalBinary ¶
func (UUID) MarshalText ¶
MarshalText implements encoding.TextMarshaler.
func (*UUID) Scan ¶
Scan implements sql.Scanner so UUIDs can be read from databases transparently. Currently, database types that map to string and []byte are supported. Please consult database-specific driver documentation for matching types.
func (*UUID) UnmarshalBinary ¶
func (*UUID) UnmarshalText ¶
UnmarshalText implements encoding.TextUnmarshaler.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
example
|
|
|
restful
command
|
|
|
work
command
|
|
|
middleware
|
|
|
Package reuseport provides TCP net.Listener with SO_REUSEPORT support.
|
Package reuseport provides TCP net.Listener with SO_REUSEPORT support. |
|
Package tcplisten provides customizable TCP net.Listener with various performance-related options:
|
Package tcplisten provides customizable TCP net.Listener with various performance-related options: |