Documentation
¶
Overview ¶
grpc.go
Index ¶
- Constants
- Variables
- func AddHealthProbe(probe HealthProbe)
- func CheckHealth() map[string]string
- func CheckPassword(password, hash string) bool
- func CloseNSQ()
- func CloseRedis()
- func Contains[S ~[]E, E comparable](s S, v E) bool
- func ContainsAny(elems Array, v any) bool
- func CurrentConfigFile() string
- func D(f string, args ...any)
- func DBType(name ...string) string
- func DecodeCursorToken(spec CursorSpec) ([]any, error)
- func DecryptAES(ciphertext string) (string, error)
- func DecryptAESBytes(ciphertext []byte) ([]byte, error)
- 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 EncodeCursorToken(fields []string, desc bool, values ...any) (string, error)
- func EncryptAES(plaintext string) (string, error)
- func EncryptAESBytes(plaintext []byte) ([]byte, error)
- func EnumFromString[T Enum](str string, mapping []string) T
- func EnumMarshalJSON[T Enum](val T, mapping []string) ([]byte, error)
- func EnumMarshalText[T Enum](v 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 EnumUnmarshalText[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 ExtractPrimaryDomain(host string) string
- func Filter[T any](slice []T, test func(T) bool) []T
- func Find(out any, args ...any) error
- func FixURI(pre, src, tag string) string
- func GetTrimmedParam(param string) string
- func GrpcCookie(ctx context.Context, cookie *http.Cookie) error
- func GrpcHeader(ctx context.Context, key string) string
- func GrpcRemoveCookie(ctx context.Context, name, path string, dom ...string) error
- func GrpcSetCookie(ctx context.Context, name, value string, exp time.Time, path string, ...) error
- func GrpcSetHeader(ctx context.Context, key string, values ...string) error
- func HashPassword(password string) (string, error)
- func HashPasswordWithCost(password string, cost int) (string, error)
- func HeaderMap(headers http.Header) map[string]string
- func Index[S ~[]E, E comparable](s S, v E) int
- func Info(f string, args ...any)
- func InitNSQ(conf Options, debug bool) error
- func IsChild() bool
- func IsErrors(v any) bool
- func IsInvalidLengthError(err error) bool
- func IsNumeric(s string) bool
- func IsRouteFallback(c Ctx) bool
- func LocalIP() (ip net.IP, err error)
- func Log(f string, args ...any)
- func LogRotateOptionsFromConfig(conf Options) []string
- func MIME(extension string) (mime string)
- func MakePath(name, dst string, args ...any) (string, string, error)
- func NSQDecodeJSON(msg *nsq.Message, v any) error
- func NSQDecodeStdJSON(msg *nsq.Message, v any) error
- func NSQDeferredPublish(topic string, delay time.Duration, body []byte) error
- func NSQDeferredPublishJSON(topic string, delay time.Duration, v any) error
- func NSQHandlerWithTimeout(timeout time.Duration, ...) nsq.HandlerFunc
- func NSQParse[T any](msg *nsq.Message) (*T, error)
- func NSQPublish(topic string, body []byte) error
- func NSQPublishJSON(topic string, v any) error
- func NSQPublishString(topic, message string) error
- func NewModel(conf Options, debug, colorful bool) (map[string]*DB, error)
- func NewNID() nid.ID
- func NewRedis(conf Options, debug bool) (map[string]*RedisClient, error)
- func NewSnID() sid.ID
- func NewXID() xid.ID
- func NormalizeHeaders(h http.Header)
- func PrintJSON(v any, tags ...any)
- func RegHandle(mods ...any)
- func RegHandleFactory(factory func() Module)
- func RegisterModule(inst module)
- func RemoteIP(h iGet, remoteAddr string) net.IP
- func Remove[T comparable](elems []T, v T) []T
- func RemoveAll[S ~[]E, E comparable](s S, v E) S
- 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 SHA256(s string) string
- func SHA256Hash(data string) string
- func SHA256HashBytes(data []byte) string
- func SaveConfigFile(conf map[string]any) error
- func StatusMessage(status int) string
- func ToAny[T any](items []T) []any
- func ToNamer(name string) string
- func ToStrings[T fmt.Stringer](items []T) []string
- func ToStringsFromAny(items []any) []string
- func Unique[S ~[]E, E comparable](s S) S
- 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) Bind(out any, debug ...bool) error
- func (c *BaseCtx) BodyParser(out any) error
- func (c *BaseCtx) Context() context.Context
- func (c *BaseCtx) Cookie(cookie *http.Cookie)
- func (c *BaseCtx) Cookies(name string) (string, error)
- func (c *BaseCtx) Core() *Core
- func (c *BaseCtx) Ctx() context.Context
- 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) FromValueXid(key string, def ...xid.ID) xid.ID
- 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) GetParamSid(key string, defaultValue ...sid.ID) (sid.ID, error)
- func (c *BaseCtx) GetParamUid(key string, defaultValue ...uid.UID) (uid.UID, error)
- func (c *BaseCtx) GetSid(key string, def ...sid.ID) (v sid.ID)
- 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) GetXid(key string, def ...xid.ID) (v xid.ID)
- func (c *BaseCtx) Host() string
- func (c *BaseCtx) JSON(data any, code ...int) error
- func (c *BaseCtx) JSONP(data any, callback ...string) error
- func (c *BaseCtx) Locals(key string, val ...any) any
- func (c *BaseCtx) Method() string
- func (c *BaseCtx) Next() error
- func (c *BaseCtx) Param(key string, defaultValue ...string) string
- 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) ParamsMaps() map[string]string
- func (c *BaseCtx) ParamsSid(key string, defaultValue ...sid.ID) (sid.ID, 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) ParamsXid(key string, defaultValue ...xid.ID) (xid.ID, 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) ReadBodyAndValidate(out any) error
- func (c *BaseCtx) Redirect(to string, stCode ...int) error
- 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) SSEComment(comment string) error
- func (c *BaseCtx) SSESend(event string, data any, id ...string) error
- func (c *BaseCtx) SSEWrite(event, data string, id ...string) error
- 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) SetResponseWriter(w ResponseWriter)
- 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 CertMagicConfig
- type ClientInfo
- 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) *BaseCtx
- 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) ConfigureGRPCClient(serviceName string, config GRPCClientConfig) error
- func (app *Core) ConfigureGRPCServer(config GRPCServerConfig) error
- func (app *Core) Conn(name ...string) *DB
- func (app *Core) DELETE(path string, handler any, middleware ...any) Router
- func (app *Core) EnableEtcdDiscovery(opts *etcd.Options) error
- func (app *Core) EnableEtcdRegistry(opts *etcd.Options) error
- func (app *Core) EnableGRPC(addr ...string) *Core
- func (app *Core) EnableWorkloadIdentity() error
- func (app *Core) ErrGroup() *errgroup.Group
- func (app *Core) EtcdRegistryIdentity() (serviceName, namespace string, ok bool)
- func (app *Core) EtcdTLSConfig() (*tls.Config, string, error)
- func (app *Core) GET(path string, handler any, middleware ...any) Router
- func (app *Core) GRPCMaxRecvMessageBytes() int
- func (app *Core) GetGRPCServer() *grpc.Server
- func (app *Core) GetModule(id string) (ModuleInfo, error)
- func (app *Core) Group(prefix string, handlers ...HandlerFuncs) Router
- func (app *Core) GrpcClient(serviceName string, opts ...grpc.DialOption) (*grpc.ClientConn, error)
- func (app *Core) GrpcClientAt(serviceName, target string) (*grpc.ClientConn, error)
- func (app *Core) HEAD(path string, handler any, middleware ...any) Router
- func (app *Core) Listen(port ...any) error
- func (app *Core) MustGrpcClient(serviceName string, opts ...grpc.DialOption) *grpc.ClientConn
- func (app *Core) NProducer() *NSQProducer
- func (app *Core) NSQDeliveryPaused() bool
- func (app *Core) NewNSQConsumer(conf NSQConsumerConfig) (*NSQConsumer, error)
- func (app *Core) OPTIONS(path string, handler any, middleware ...any) Router
- func (app *Core) OnShutdown(fn func())
- 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) ProcessedHandler(hand any) HandlerFuncs
- func (app *Core) RConn(name ...string) *RedisClient
- func (app *Core) RegisterGRPCService(registerFunc func(*grpc.Server))
- func (app *Core) ReleaseCtx(c Ctx)
- func (app *Core) RemoveHandle(methods []string, uri string)
- func (app *Core) ReplaceHandle(methods []string, oldURI, uri string, handler any, middleware ...HandlerFunc) Router
- func (app *Core) RotateWorkloadIntermediate() error
- 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) ServingReady() bool
- func (app *Core) ShutdownWithTimeout(timeout time.Duration) error
- func (app *Core) Static(relativePath, root string, config ...StaticConfig) Router
- func (app *Core) StaticFS(relativePath string, fs http.FileSystem, config ...StaticConfig) Router
- func (app *Core) StaticFile(relativePath, dirname string, config ...StaticConfig) Router
- func (app *Core) StaticFileFS(relativePath, dirname string, fs http.FileSystem, config ...StaticConfig) Router
- func (app *Core) TRACE(path string, handler any, middleware ...any) Router
- func (app *Core) Use(fn ...any) Router
- func (app *Core) UseCertificateManager(manager *certificate.Manager, httpAddress string) error
- func (app *Core) WorkloadClientCredentials(target string) (credentials.TransportCredentials, error)
- func (app *Core) WorkloadClientTLSConfig(target string) (*tls.Config, error)
- func (app *Core) WorkloadIdentityStats() (workload.Stats, error)
- func (app *Core) WorkloadIssuerStats() (workload.IssuerStats, error)
- func (app *Core) WorkloadServerCredentials() (credentials.TransportCredentials, error)
- func (app *Core) WorkloadServerTLSConfig() (*tls.Config, error)
- type Ctx
- type CursorDirection
- type CursorSpec
- type DB
- type Date
- type EncryptedConfigFile
- func (s *EncryptedConfigFile) Commit(expectedRevision, preparedRevision string) error
- func (s *EncryptedConfigFile) Discard(preparedRevision string) error
- func (s *EncryptedConfigFile) Prepare(expectedRevision string, next Options) (string, error)
- func (s *EncryptedConfigFile) Snapshot() (Options, string, error)
- type Enum
- type Error
- type ErrorHandler
- type Errors
- type EventData
- type EventHub
- func (h *EventHub) Broadcast(data EventData)
- func (h *EventHub) Close()
- func (h *EventHub) Get(c Ctx)
- func (h *EventHub) PostData(c Ctx)
- func (h *EventHub) Register(c chan EventData, id ...string)
- func (h *EventHub) SendTo(id string, data EventData)
- func (h *EventHub) UnRegister(c chan EventData, id ...string)
- type FindsMode
- type FindsParams
- type FindsResult
- type GRPCClientConfig
- type GRPCCtx
- func (c *GRPCCtx) ClientIP() string
- func (c *GRPCCtx) Cookie(name string) (string, error)
- func (c *GRPCCtx) GetHeader(key string) string
- func (c *GRPCCtx) HeaderValues(key string) []string
- func (c *GRPCCtx) OutgoingContext(md metadata.MD) context.Context
- func (c *GRPCCtx) RemoveCookie(name, path string, domain ...string) error
- func (c *GRPCCtx) RequestMetadata() metadata.MD
- func (c *GRPCCtx) SetCookie(name, value string, exp time.Time, path string, args ...any) error
- func (c *GRPCCtx) SetHeader(key string, values ...string) error
- func (c *GRPCCtx) StdContext() context.Context
- func (c *GRPCCtx) WriteCookie(cookie *http.Cookie) error
- type GRPCServerConfig
- 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 ...HandlerFuncs) Router
- 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 HealthProbe
- type HookWriter
- type IModel
- type Int
- type IntID
- type IntMoneydeprecated
- 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 any) error
- func (j JSON) String() string
- func (j *JSON) UnmarshalJSON(b []byte) error
- func (j JSON) Value() (driver.Value, error)
- type LogMonitor
- type LogRotateConfig
- 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 Moneydeprecated
- 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) Scan(value any) error
- 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
- func (m Money) Value() (driver.Value, error)
- type NSQConsumer
- func (nc *NSQConsumer) ChangeMaxInFlight(maxInFlight int)
- func (nc *NSQConsumer) DeliveryPaused() bool
- func (nc *NSQConsumer) DeliveryState() NSQDeliveryState
- func (nc *NSQConsumer) IsStarved() bool
- func (nc *NSQConsumer) RecoverDelivery(key string, budget uint32, deadline time.Time) (NSQDeliveryRecovery, error)
- func (nc *NSQConsumer) Start(handler NSQHandlerFunc) error
- func (nc *NSQConsumer) StartAsync(handler NSQHandlerFunc) error
- func (nc *NSQConsumer) Stats() *nsq.ConsumerStats
- func (nc *NSQConsumer) Stop()
- type NSQConsumerBuilder
- func (b *NSQConsumerBuilder) Build() (*NSQConsumer, error)
- func (b *NSQConsumerBuilder) BuildAndStart(handler NSQHandlerFunc) (*NSQConsumer, error)
- func (b *NSQConsumerBuilder) WithConcurrency(n int) *NSQConsumerBuilder
- func (b *NSQConsumerBuilder) WithLookupd(addrs ...string) *NSQConsumerBuilder
- func (b *NSQConsumerBuilder) WithMaxAttempts(n uint16) *NSQConsumerBuilder
- func (b *NSQConsumerBuilder) WithMaxBackoff(d time.Duration) *NSQConsumerBuilder
- func (b *NSQConsumerBuilder) WithMaxInFlight(n int) *NSQConsumerBuilder
- func (b *NSQConsumerBuilder) WithMsgTimeout(d time.Duration) *NSQConsumerBuilder
- func (b *NSQConsumerBuilder) WithNSQD(addrs ...string) *NSQConsumerBuilder
- type NSQConsumerConfig
- type NSQDeliveryRecovery
- type NSQDeliveryState
- type NSQHandlerContext
- type NSQHandlerFunc
- type NSQProducer
- func (p *NSQProducer) DeferredPublish(topic string, delay time.Duration, body []byte) error
- func (p *NSQProducer) DeferredPublishJSON(topic string, delay time.Duration, v any) error
- func (p *NSQProducer) MultiPublish(topic string, bodies [][]byte) error
- func (p *NSQProducer) Ping() error
- func (p *NSQProducer) Publish(topic string, body []byte) error
- func (p *NSQProducer) PublishJSON(topic string, v any) error
- func (p *NSQProducer) PublishString(topic, message string) error
- func (p *NSQProducer) Stop()
- type NextPage
- type NextPages
- type Options
- func (d Options) As(k string, v any) error
- func (opt Options) ExpandEnv()
- func (opt *Options) GetAs(k string, v any) error
- func (opt *Options) GetBool(k string, def ...bool) bool
- func (opt *Options) GetDuration(k string, def ...time.Duration) time.Duration
- 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) GetPathBool(path string, def ...bool) bool
- func (opt *Options) GetPathInt(path string, def ...int) int
- func (opt *Options) GetPathString(path string, def ...string) string
- func (opt *Options) GetPathStrings(path string, def ...[]string) []string
- 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 Page
- type Pages
- type RecoveryFunc
- type RedisClient
- func (r *RedisClient) BitCount(ctx context.Context, key string, bitCount *redis.BitCount) (int64, error)
- func (r *RedisClient) Close() error
- func (r *RedisClient) Decr(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) Delete(ctx context.Context, keys ...string) error
- func (r *RedisClient) Eval(ctx context.Context, script string, keys []string, args ...any) (any, error)
- func (r *RedisClient) EvalSha(ctx context.Context, sha1 string, keys []string, args ...any) (any, error)
- func (r *RedisClient) Exists(ctx context.Context, key string) (bool, error)
- func (r *RedisClient) Expire(ctx context.Context, key string, ttl time.Duration) error
- func (r *RedisClient) Get(ctx context.Context, key string) (string, error)
- func (r *RedisClient) GetBit(ctx context.Context, key string, offset int64) (int64, error)
- func (r *RedisClient) GetInt(ctx context.Context, key string) (int, error)
- func (r *RedisClient) GetJSON(ctx context.Context, key string, v any) error
- func (r *RedisClient) HDel(ctx context.Context, key string, fields ...string) error
- func (r *RedisClient) HExists(ctx context.Context, key, field string) (bool, error)
- func (r *RedisClient) HGet(ctx context.Context, key, field string) (string, error)
- func (r *RedisClient) HGetAll(ctx context.Context, key string) (map[string]string, error)
- func (r *RedisClient) HGetJSON(ctx context.Context, key, field string, v any) error
- func (r *RedisClient) HIncrBy(ctx context.Context, key, field string, incr int64) (int64, error)
- func (r *RedisClient) HLen(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) HSet(ctx context.Context, key string, values ...any) error
- func (r *RedisClient) HSetJSON(ctx context.Context, key, field string, value any) error
- func (r *RedisClient) Incr(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) IncrBy(ctx context.Context, key string, value int64) (int64, error)
- func (r *RedisClient) IncrWithTTL(ctx context.Context, key string, ttl time.Duration) (int64, error)
- func (r *RedisClient) LLen(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) LPop(ctx context.Context, key string) (string, error)
- func (r *RedisClient) LPush(ctx context.Context, key string, values ...any) error
- func (r *RedisClient) LRange(ctx context.Context, key string, start, stop int64) ([]string, error)
- func (r *RedisClient) NewStreamConsumer(conf StreamConsumerConfig) *StreamConsumer
- func (r *RedisClient) Ping(ctx context.Context) error
- func (r *RedisClient) Pipeline() redis.Pipeliner
- func (r *RedisClient) Pipelined(ctx context.Context, fn func(redis.Pipeliner) error) ([]redis.Cmder, error)
- func (r *RedisClient) Publish(ctx context.Context, channel string, message any) error
- func (r *RedisClient) RPop(ctx context.Context, key string) (string, error)
- func (r *RedisClient) RPush(ctx context.Context, key string, values ...any) error
- func (r *RedisClient) SAdd(ctx context.Context, key string, members ...any) error
- func (r *RedisClient) SCard(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) SIsMember(ctx context.Context, key string, member any) (bool, error)
- func (r *RedisClient) SMembers(ctx context.Context, key string) ([]string, error)
- func (r *RedisClient) SRem(ctx context.Context, key string, members ...any) error
- func (r *RedisClient) Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanCmd
- func (r *RedisClient) ScriptLoad(ctx context.Context, script string) (string, error)
- func (r *RedisClient) Set(ctx context.Context, key string, value any, ttl ...time.Duration) error
- func (r *RedisClient) SetBit(ctx context.Context, key string, offset int64, value int) error
- func (r *RedisClient) SetJSON(ctx context.Context, key string, value any, ttl ...time.Duration) error
- func (r *RedisClient) Subscribe(ctx context.Context, channel string, handler func(string)) error
- func (r *RedisClient) TTL(ctx context.Context, key string) (time.Duration, error)
- func (r *RedisClient) TxPipeline() redis.Pipeliner
- func (r *RedisClient) XAck(ctx context.Context, stream, group string, ids ...string) error
- func (r *RedisClient) XAdd(ctx context.Context, stream string, fields map[string]any, id ...string) (string, error)
- func (r *RedisClient) XAddJSON(ctx context.Context, stream string, value any, id ...string) (string, error)
- func (r *RedisClient) XClaim(ctx context.Context, stream, group, consumer string, minIdleTime time.Duration, ...) ([]StreamMessage, error)
- func (r *RedisClient) XDel(ctx context.Context, stream string, ids ...string) (int64, error)
- func (r *RedisClient) XGroupCreate(ctx context.Context, stream, group, startID string) error
- func (r *RedisClient) XGroupDestroy(ctx context.Context, stream, group string) error
- func (r *RedisClient) XLen(ctx context.Context, stream string) (int64, error)
- func (r *RedisClient) XPending(ctx context.Context, stream, group string) (*redis.XPending, error)
- func (r *RedisClient) XRange(ctx context.Context, stream, start, stop string, count ...int64) ([]StreamMessage, error)
- func (r *RedisClient) XRead(ctx context.Context, stream string, startID string, count ...int64) ([]StreamMessage, error)
- func (r *RedisClient) XReadGroup(ctx context.Context, stream, group, consumer string, count int64, ...) ([]StreamMessage, error)
- func (r *RedisClient) XTrim(ctx context.Context, stream string, maxLen int64) error
- func (r *RedisClient) ZAdd(ctx context.Context, key string, members ...redis.Z) error
- func (r *RedisClient) ZCard(ctx context.Context, key string) (int64, error)
- func (r *RedisClient) ZIncrBy(ctx context.Context, key string, increment float64, member string) (float64, error)
- func (r *RedisClient) ZRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)
- func (r *RedisClient) ZRem(ctx context.Context, key string, members ...any) error
- func (r *RedisClient) ZRevRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)
- func (r *RedisClient) ZScore(ctx context.Context, key string, member string) (float64, error)
- type ResponseWriter
- type RestfulDefine
- type RotatingLogWriter
- type RouteNode
- type Router
- type SModels
- type StaticConfig
- type StreamConsumer
- type StreamConsumerConfig
- type StreamMessage
- 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 GatewayClientIPMetadata = "core-client-ip"
GatewayClientIPMetadata 是 Gateway 保留并覆盖写入的客户端 IP 字段。
const VERSION = "v3"
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] MethodAll = Methods[METHOD_ALL] )
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 ( // ErrGRPCServerAlreadyInitialized 表示 gRPC server 已创建,不能再改变 transport 或 interceptor。 ErrGRPCServerAlreadyInitialized = errors.New("grpc server already initialized") // ErrGRPCServerAlreadyConfigured 表示同一个 Core 实例已经完成一次 gRPC server 配置。 ErrGRPCServerAlreadyConfigured = errors.New("grpc server already configured") ErrGRPCTLSSharedAddress = errors.New("grpc transport credentials require a dedicated grpc address") // ErrEtcdDiscoveryConfigurationChanged protects clients bound to an existing Discovery. ErrEtcdDiscoveryConfigurationChanged = errors.New("core: etcd discovery configuration change requires a new Core instance") )
var ( ErrGRPCClientAlreadyInitialized = errors.New("grpc client service already initialized") ErrGRPCClientAlreadyConfigured = errors.New("grpc client service already configured") ErrGRPCClientServiceRequired = errors.New("grpc client service name required") ErrGRPCClientTargetRequired = errors.New("grpc client target required") ErrGRPCClientCredentialsRequired = errors.New("grpc client transport credentials required") ErrGRPCClientDialOptionsConflict = errors.New("configured grpc client does not accept legacy dial options") )
var ( DefaultErrorWriter io.Writer = os.Stderr LogHub = NewLogMonitor() )
DefaultErrorWriter is the default io.Writer used by Gin to debug errors
var ( SnID *sid.SnowflakeID XID *xid.Generator )
var ( // AESKey AES-256 密钥(32字节) AESKey = []byte("this-is-a-32-byte-key-for-aes256") )
var DefaultLogRotateOptions = []string{
"size: 300M",
"daily",
"rotate: 30",
"compress",
"delaycompress: 24h",
"missingok",
"notifempty",
"copytruncate",
}
var (
DefaultOutput = io.Discard
)
var ErrConfigFileConflict = errors.New("configuration file revision conflict")
ErrConfigFileConflict 表示正式配置的密文版本已变化。
ErrConfigFileUnavailable 表示配置无法安全读取或持久化,不包含路径、密钥或明文。
var ErrInvalidCursor = errors.New("core: invalid cursor")
var ErrInvalidQuery = errors.New("core: invalid query")
ErrInvalidQuery indicates an invalid filter field or query control parameter.
var (
ErrInvalidValidationType = NewError(400, "验证类型必须是结构体指针")
)
全局验证器实例 自定义错误类型
var ErrNSQRecoveryConflict = errors.New("nsq recovery command conflict")
var (
Methods = []string{
"GET",
"POST",
"HEAD",
"PUT",
"DELETE",
"OPTIONS",
"CONNECT",
"TRACE",
"PATCH",
"ALL",
"USE",
}
)
var UuidNil = UUID{uuid.Nil}
Functions ¶
func AddHealthProbe ¶ added in v3.1.30
func AddHealthProbe(probe HealthProbe)
AddHealthProbe 注册健康探针。用于检查 DB/Redis/等依赖健康状态。 在启动时调用 NewModel/NewRedis 后注册对应的 ping 探针。
func CheckHealth ¶ added in v3.1.30
CheckHealth 执行所有注册的健康探针,返回失败列表。
func CheckPassword ¶ added in v3.1.16
CheckPassword 验证密码
func Contains ¶
func Contains[S ~[]E, E comparable](s S, v E) bool
func ContainsAny ¶
func CurrentConfigFile ¶ added in v3.1.65
func CurrentConfigFile() string
CurrentConfigFile 返回最近一次成功加载配置时记录的绝对路径,尚未成功加载时返回空串。
func DecodeCursorToken ¶ added in v3.1.40
func DecodeCursorToken(spec CursorSpec) ([]any, error)
DecodeCursorToken validates a token against spec and returns its ordered key values. JSON numbers are returned as json.Number so 64-bit IDs stay exact.
func DecryptAES ¶ added in v3.1.16
DecryptAES AES-256-GCM 解密
func DecryptAESBytes ¶ added in v3.1.16
DecryptAESBytes AES-256-GCM 解密
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 EncodeCursorToken ¶ added in v3.1.40
EncodeCursorToken returns an opaque, URL-safe token that is bound to the supplied fields and sort direction. Values must follow the same order as fields.
func EncryptAES ¶ added in v3.1.16
EncryptAES AES-256-GCM 加密
func EncryptAESBytes ¶ added in v3.1.16
EncryptAESBytes AES-256-GCM 加密
func EnumFromString ¶
EnumFromString 字符串转枚举值
func TypeXFromString(str string) TypeX {
return EnumFromString[TypeX](str, TypeXMap)
}
func EnumMarshalJSON ¶
EnumMarshalJSON 枚举 JSON 序列化
func EnumMarshalText ¶ added in v3.1.6
EnumMarshalText 将枚举格式化为文本;未定义的索引返回错误。
func EnumString ¶
EnumString 枚举值转字符串
func (s TypeX) String() string {
return EnumString(s, TypeXMap)
}
func EnumUnmarshalJSON ¶
EnumUnmarshalJSON 枚举 JSON 反序列化
func EnumUnmarshalText ¶ added in v3.1.6
func EqualFold ¶
func EqualFold[S byteSeq](b, s S) bool
EqualFold tests ascii strings or bytes for equality case-insensitively
func ExtractPrimaryDomain ¶ added in v3.1.10
ExtractPrimaryDomain 提取一级域名(主域名) 示例:
"webin.work" -> "webin.work" "www.webin.work" -> "webin.work" "api.webin.work" -> "webin.work" "customer.com" -> "customer.com" "www.customer.com" -> "customer.com"
func Filter ¶ added in v3.0.7
Filter 过滤
activeUsers := core.Filter(users, func(u User) bool {
return u.Status == "active"
})
func GetTrimmedParam ¶
GetTrimmedParam trims the ':' & '?' from a string
func GrpcCookie ¶ added in v3.1.45
GrpcCookie queues a complete cookie without applying defaults or escaping its value, like BaseCtx.Cookie. Invalid cookies return an error instead of being silently dropped or sanitized. The caller-owned cookie is not modified.
func GrpcRemoveCookie ¶ added in v3.1.45
GrpcRemoveCookie mirrors BaseCtx.RemoveCookie, including its unchanged path and optional Domain (the first value wins). Use the original Path/Domain.
func GrpcSetCookie ¶ added in v3.1.45
func GrpcSetCookie(ctx context.Context, name, value string, exp time.Time, path string, args ...any) error
GrpcSetCookie mirrors BaseCtx.SetCookie: empty path becomes "/", value is URL-escaped, SameSite defaults to Lax, a case-insensitive "httponly" string enables HttpOnly, other strings set Domain, and bools set Secure. Empty Domain falls back to the current Core server's domain config. Unknown args are ignored. Use GrpcCookie for explicit SameSite, MaxAge and a host-only cookie.
func GrpcSetHeader ¶ added in v3.1.45
GrpcSetHeader queues HTTP response header values in gRPC initial metadata. Repeated calls append values, as with grpc.SetHeader. Gateway converts only this explicit core-http-<lowercase-name>-bin contract, including on RPC errors. Transport headers and invalid names/values are rejected before queuing. Names must also fit the gRPC metadata alphabet (letters, digits, -_.). Call before sending initial headers; ctx must be the current server RPC context.
func HashPassword ¶ added in v3.1.16
HashPassword 使用 bcrypt 哈希密码(使用默认 cost)
func HashPasswordWithCost ¶ added in v3.1.16
HashPasswordWithCost 使用 bcrypt 哈希密码,可指定 cost
func Index ¶
func Index[S ~[]E, E comparable](s S, v E) int
func IsInvalidLengthError ¶
IsInvalidLengthError is matcher function for custom error invalidLengthError
func IsRouteFallback ¶ added in v3.1.28
IsRouteFallback reports whether the current handler chain is running because an OPTIONS request did not match an explicit route.
func LogRotateOptionsFromConfig ¶ added in v3.1.19
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 NSQDecodeJSON ¶ added in v3.1.17
NSQDecodeJSON 从 nsq.Message.Body 解析 JSON
func NSQDecodeStdJSON ¶ added in v3.1.17
NSQDecodeStdJSON 从 nsq.Message.Body 解析 JSON(标准库)
func NSQDeferredPublish ¶ added in v3.1.17
NSQDeferredPublish 快速延迟发布
func NSQDeferredPublishJSON ¶ added in v3.1.17
NSQDeferredPublishJSON 快速延迟发布 JSON
func NSQHandlerWithTimeout ¶ added in v3.1.17
func NSQHandlerWithTimeout(timeout time.Duration, handler func(ctx context.Context, msg *nsq.Message) error) nsq.HandlerFunc
NSQHandlerWithTimeout 包装 handler,为每条消息创建带超时的 context
func NSQPublish ¶ added in v3.1.17
NSQPublish 快速发布消息到指定 topic
func NSQPublishJSON ¶ added in v3.1.17
NSQPublishJSON 快速发布 JSON 消息
func NSQPublishString ¶ added in v3.1.17
NSQPublishString 快速发布字符串消息
func NewRedis ¶ added in v3.1.17
func NewRedis(conf Options, debug bool) (map[string]*RedisClient, error)
NewRedis 根据配置初始化 Redis 连接 支持单实例和多实例两种配置格式
func NormalizeHeaders ¶ added in v3.1.7
func RegHandleFactory ¶ added in v3.1.68
func RegHandleFactory(factory func() Module)
RegHandleFactory registers a per-application Handler factory. It must return a fresh pointer each time; use this API when multiple Core instances coexist. Registration evaluates the factory once to determine its stable module ID.
func RegisterModule ¶
func RegisterModule(inst module)
func RemoteIP ¶ added in v3.1.10
RemoteIP 默认信任私网和回环代理,不读取应用配置。 可信对端优先解析 XFF,仅缺少 XFF 时尝试单个 X-Real-IP。 无效 RemoteAddr 返回 nil。
func RemoveAll ¶ added in v3.1.10
func RemoveAll[S ~[]E, E comparable](s S, v E) S
RemoveAll 删除所有匹配的元素
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 SHA256Hash ¶ added in v3.1.16
SHA256Hash 计算 SHA-256 哈希值(string 版本)
func SHA256HashBytes ¶ added in v3.1.16
SHA256HashBytes 计算 SHA-256 哈希值([]byte 版本)
func SaveConfigFile ¶
func StatusMessage ¶
StatusMessage returns the correct message for the provided HTTP statuscode
func ToStringsFromAny ¶
ToStringsFromAny 把 []any 转换成 []string
func Unique ¶ added in v3.1.10
func Unique[S ~[]E, E comparable](s S) S
Unique 去重
uniqueScopes := core.Unique(scopes)
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) FromValueXid ¶ added in v3.1.3
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) GetParamSid ¶ added in v3.0.7
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) ParamsMaps ¶ added in v3.1.10
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) ReadBodyAndValidate ¶ added in v3.1.30
ReadBodyAndValidate 读取请求体并验证,返回统一的错误响应格式。 先调用 c.ReadBody(out) 解析,再调用 c.Validate(out) 验证。 解析失败返回 400,验证失败返回 422。 使用方式:
var req CreateUserReq
if err := c.ReadBodyAndValidate(&req); err != nil {
return err
}
func (*BaseCtx) RedirectJS ¶
func (*BaseCtx) RemoteIP ¶
RemoteIP 空 trusted_proxies 配置时信任私网/回环;非空时仅信任配置范围。 XFF 从右向左检查,仅缺少 XFF 时尝试单个 X-Real-IP;无效头回退 TCP 对端。 代理必须覆盖转发头或向 XFF 追加实际来源。
func (*BaseCtx) RemoveCookie ¶
func (*BaseCtx) Response ¶
func (c *BaseCtx) Response() ResponseWriter
ResponseWriter implements Ctx.
func (*BaseCtx) SSEComment ¶ added in v3.1.30
SSEComment sends an SSE comment line (used for heartbeat/keepalive). The SSE spec says lines starting with ":" are comments and ignored by clients.
func (*BaseCtx) SSESend ¶ added in v3.1.30
SSESend sends a structured SSE event, auto-serializing data to JSON.
func (*BaseCtx) SSEWrite ¶ added in v3.1.30
SSEWrite writes a single Server-Sent Event to the response. Handles proper formatting of id, event, and data fields. Multi-line data is automatically prefixed with "data: " on each line.
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) SetResponseWriter ¶ added in v3.1.61
func (c *BaseCtx) SetResponseWriter(w ResponseWriter)
SetResponseWriter replaces the current response writer. Middleware must restore the previous writer before returning; the writer must not outlive the request.
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 CertMagicConfig ¶ added in v3.1.10
type ClientInfo ¶ added in v3.1.10
func ExtractClientInfo ¶ added in v3.1.10
func ExtractClientInfo(ctx context.Context) *ClientInfo
ExtractClientInfo 对 Core 托管的 RPC 使用 TrustGateway 策略;未设置时 根据实际对端 IP 信任私网/回环。仅采信单值合法 core-client-ip, 其它情况返回 gRPC 对端,不解析原始 IP 转发头。
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
EtcdDiscovery *etcd.Discovery
// contains filtered or unexported fields
}
func (*Core) AcquireCtx ¶
func (*Core) AddHandle ¶
func (app *Core) AddHandle(methods []string, uri string, group *Group, handler any, middleware ...HandlerFunc) Router
core.go - AddHandle 方法
func (*Core) ConfigureGRPCClient ¶ added in v3.1.29
func (app *Core) ConfigureGRPCClient(serviceName string, config GRPCClientConfig) error
ConfigureGRPCClient 必须在指定逻辑服务首次建立连接前调用。
func (*Core) ConfigureGRPCServer ¶ added in v3.1.28
func (app *Core) ConfigureGRPCServer(config GRPCServerConfig) error
ConfigureGRPCServer 在 gRPC server 初始化前配置 transport 和 interceptor。 每个 Core 实例只允许配置一次,避免后续调用静默覆盖安全策略。
func (*Core) Conn ¶ added in v3.1.68
Conn returns this application's database, independently of the global Conn default.
func (*Core) EnableEtcdDiscovery ¶ added in v3.1.10
EnableEtcdDiscovery 启用 etcd 服务发现
func (*Core) EnableEtcdRegistry ¶ added in v3.1.10
EnableEtcdRegistry 启用 etcd 服务注册 当 opts 为 nil 时,从配置文件读取;当 opts 已设置字段时,保留用户值
func (*Core) EnableGRPC ¶ added in v3.1.10
EnableGRPC 启用 gRPC 支持
func (*Core) EnableWorkloadIdentity ¶ added in v3.1.51
EnableWorkloadIdentity 在首次创建 gRPC 服务端或客户端前准备本进程身份。 未启用配置时不改变既有 transport;启用后任何初始化失败都拒绝明文回退。
func (*Core) EtcdRegistryIdentity ¶ added in v3.1.35
EtcdRegistryIdentity returns the identity installed by the most recent successful EnableEtcdRegistry call. Failed replacements leave this snapshot unchanged.
func (*Core) EtcdTLSConfig ¶ added in v3.1.51
EtcdTLSConfig 为 Registry、Discovery 和 Gateway 自建连接读取相同 etcd TLS 配置。
func (*Core) GRPCMaxRecvMessageBytes ¶ added in v3.1.66
GRPCMaxRecvMessageBytes 返回通用 gRPC 接收上限,单位为字节。 未配置、非正值或超过64MiB均安全回落4MiB;不会把零解释为无限制。
func (*Core) GetGRPCServer ¶ added in v3.1.10
GetGRPCServer 获取 gRPC 服务器实例(用于注册服务)
func (*Core) GrpcClient ¶ added in v3.1.10
func (app *Core) GrpcClient(serviceName string, opts ...grpc.DialOption) (*grpc.ClientConn, error)
GrpcClient 创建 gRPC 客户端连接(基于 etcd 服务发现)
func (*Core) GrpcClientAt ¶ added in v3.1.29
func (app *Core) GrpcClientAt(serviceName, target string) (*grpc.ClientConn, error)
GrpcClientAt 使用明确 target 建立连接,并与服务发现连接共用同一份每服务安全配置。
func (*Core) MustGrpcClient ¶ added in v3.1.13
func (app *Core) MustGrpcClient(serviceName string, opts ...grpc.DialOption) *grpc.ClientConn
MustGrpcClient 创建 gRPC 客户端连接,失败则 panic
func (*Core) NProducer ¶ added in v3.1.68
func (app *Core) NProducer() *NSQProducer
NProducer returns this application's NSQ producer.
func (*Core) NSQDeliveryPaused ¶ added in v3.1.74
NSQDeliveryPaused 只检查本应用拥有的消费者,不执行网络访问。
func (*Core) NewNSQConsumer ¶ added in v3.1.68
func (app *Core) NewNSQConsumer(conf NSQConsumerConfig) (*NSQConsumer, error)
NewNSQConsumer binds authentication and shutdown to this application, rather than the most recently initialized process-wide producer. Explicit AuthSecret wins.
func (*Core) ProcessedHandler ¶ added in v3.1.11
func (app *Core) ProcessedHandler(hand any) HandlerFuncs
func (*Core) RConn ¶ added in v3.1.68
func (app *Core) RConn(name ...string) *RedisClient
RConn returns this application's Redis client.
func (*Core) RegisterGRPCService ¶ added in v3.1.10
RegisterGRPCService 注册 gRPC 服务
func (*Core) ReleaseCtx ¶
func (*Core) RemoveHandle ¶ added in v3.1.17
func (*Core) ReplaceHandle ¶ added in v3.1.68
func (app *Core) ReplaceHandle(methods []string, oldURI, uri string, handler any, middleware ...HandlerFunc) Router
ReplaceHandle replaces a route under one routing lock per HTTP method. Existing in-flight requests keep their handler chain. Parameter names may change provided no other route shares an incompatible parameter position.
func (*Core) RotateWorkloadIntermediate ¶ added in v3.1.51
RotateWorkloadIntermediate 供受控运维更新中间 CA,不改变根信任;根私钥离线时明确拒绝。
func (*Core) ServingReady ¶ added in v3.1.65
ServingReady 表示传输、工作负载、路由发布及注册就绪步骤均已成功完成。 该状态用于运行态观测,不替代具体业务依赖的健康检查。
func (*Core) ShutdownWithTimeout ¶ added in v3.1.30
ShutdownWithTimeout bounds service withdrawal, transport drain, and cleanup. Legacy OnShutdown hooks cannot be forcibly canceled; a deadline still closes HTTP/gRPC transports and returns while an uncooperative hook finishes later.
func (*Core) Static ¶
func (app *Core) Static(relativePath, root string, config ...StaticConfig) Router
func (*Core) StaticFS ¶
func (app *Core) StaticFS(relativePath string, fs http.FileSystem, config ...StaticConfig) Router
func (*Core) StaticFile ¶
func (app *Core) StaticFile(relativePath, dirname string, config ...StaticConfig) Router
StaticFile static file
app.StaticFile("/favicon.ico", "./favicon.ico")
func (*Core) StaticFileFS ¶
func (app *Core) StaticFileFS(relativePath, dirname string, fs http.FileSystem, config ...StaticConfig) Router
StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead..
app.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false})
func (*Core) UseCertificateManager ¶ added in v3.1.59
func (app *Core) UseCertificateManager(manager *certificate.Manager, httpAddress string) error
UseCertificateManager 将动态证书接入已有 HTTPS listener,并托管可选的 HTTP-01 listener。 必须在 Run/Serve 前调用;httpAddress 为空时由部署层转发挑战到 manager.HTTPHandler。 成功后由 Core 在关闭时释放 manager;证书状态和域名归属仍由调用方管理。
func (*Core) WorkloadClientCredentials ¶ added in v3.1.51
func (app *Core) WorkloadClientCredentials(target string) (credentials.TransportCredentials, error)
WorkloadClientCredentials 为专用内部客户端复用身份并验证目标逻辑服务。
func (*Core) WorkloadClientTLSConfig ¶ added in v3.1.71
WorkloadClientTLSConfig verifies the logical target and reads renewed certificates at handshake time.
func (*Core) WorkloadIdentityStats ¶ added in v3.1.51
WorkloadIdentityStats 返回不含凭据的本进程申请与有效期快照。
func (*Core) WorkloadIssuerStats ¶ added in v3.1.51
func (app *Core) WorkloadIssuerStats() (workload.IssuerStats, error)
WorkloadIssuerStats 返回签发器的无秘密统计,不把 CA 状态暴露到普通业务接口。
func (*Core) WorkloadServerCredentials ¶ added in v3.1.51
func (app *Core) WorkloadServerCredentials() (credentials.TransportCredentials, error)
WorkloadServerCredentials 为专用内部 listener 复用当前进程的动态身份。
type Ctx ¶
type Ctx interface {
Context() context.Context // Request().Context()
Ctx() context.Context
Host() string
Response() ResponseWriter // Response() return http.ResponseWriter
SetResponseWriter(ResponseWriter) // Replace the writer for the current request; middleware must restore it.
Request() *http.Request // Request() return *http.Request
RedirectJS(to string, msg ...string) // use js redirect
Redirect(to string, stCode ...int) error // 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
Bind(out any, debug ...bool) error // ReadBody alias read put post form data 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
ParamsMaps() map[string]string
Params(key string, defaultValue ...string) string // get Params data e.g c.Params("param")
Param(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
GetParamSid(key string, defaultValue ...sid.ID) (sid.ID, error) // get Param ID type, return sid.Nil if failed
ParamsSid(key string, defaultValue ...sid.ID) (sid.ID, error) // get Param ID type, return sid.Nil if failed
ParamsXid(key string, defaultValue ...xid.ID) (xid.ID, error) // get Param XID type, return xid.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
FormFile(key string) (*multipart.FileHeader, error) // get form file
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
FromValueXid(key string, def ...xid.ID) xid.ID // parse form value to xid
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)
Locals(key string, val ...any) any // set get local ver
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)
GetXid(key string, def ...xid.ID) (v xid.ID)
GetSid(key string, def ...sid.ID) (v sid.ID)
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
// SSE 相关
SSEWrite(event, data string, id ...string) error // 写入单条 SSE 事件
SSESend(event string, data any, id ...string) error // 发送结构化 SSE 事件(自动序列化 data)
SSEComment(comment string) error // 发送 SSE 注释(心跳)
// SSE 相关结束
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 CursorDirection ¶ added in v3.1.40
type CursorDirection string
const ( CursorDirectionNext CursorDirection = "next" CursorDirectionPrev CursorDirection = "prev" )
type CursorSpec ¶ added in v3.1.40
type CursorSpec struct {
Token string
Direction CursorDirection
Fields []string
Desc bool
}
CursorSpec defines a stable keyset order and the optional position to resume from. Fields must contain either a unique column or an ordered column followed by a unique tie-breaker, for example []string{"id"} or []string{"created_at", "id"}.
type DB ¶
type EncryptedConfigFile ¶ added in v3.1.65
type EncryptedConfigFile struct {
// contains filtered or unexported fields
}
EncryptedConfigFile 对部署侧指定的可信 .dat 文件提供跨进程的原子版本交换。 配置目录必须可写;预备文件和永久锁文件只保存密文或锁状态。
func NewEncryptedConfigFile ¶ added in v3.1.65
func NewEncryptedConfigFile(path string) (*EncryptedConfigFile, error)
NewEncryptedConfigFile 校验配置、密钥与目录,拒绝链接和会在启动时覆盖配置的模板。
func (*EncryptedConfigFile) Commit ¶ added in v3.1.65
func (s *EncryptedConfigFile) Commit(expectedRevision, preparedRevision string) error
Commit 仅在版本匹配时原子替换正式配置,重复提交已生效版本返回成功。
func (*EncryptedConfigFile) Discard ¶ added in v3.1.65
func (s *EncryptedConfigFile) Discard(preparedRevision string) error
Discard 删除尚未使用的预备密文;文件已不存在时返回成功。
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
func (*Error) GRPCStatus ¶ added in v3.1.16
GRPCStatus 实现 gRPC 状态接口,让 status.FromError 能正常工作
type ErrorHandler ¶
type EventData ¶
type EventHub ¶
type EventHub struct {
// contains filtered or unexported fields
}
func NewEventHub ¶
func (*EventHub) Register ¶
Register 将管道的发送和关闭所有权交给 Hub;调用方只接收,不得自行关闭或复用已退役管道。 同一活动管道重复注册幂等;一个管道的多个 ID 别名共享同一生命周期。
func (*EventHub) UnRegister ¶
UnRegister 仅清理对应管道;旧连接退出不能移除同 ID 的新连接。
type FindsParams ¶ added in v3.1.39
type FindsParams struct {
Where *Map
DB *DB
Mode FindsMode
Cursor *CursorSpec
Extra any
}
type FindsResult ¶ added in v3.1.39
type FindsResult[T any] struct { P int `json:"p"` L int `json:"l"` Total *int64 `json:"total,omitempty"` Next *bool `json:"next,omitempty"` Prev *bool `json:"prev,omitempty"` NextCursor string `json:"next_cursor,omitempty"` PrevCursor string `json:"prev_cursor,omitempty"` CursorHasNext *bool `json:"has_next,omitempty"` CursorHasPrev *bool `json:"has_prev,omitempty"` Data []T `json:"data"` Extra any `json:"extra,omitempty"` }
func Finds ¶ added in v3.1.39
func Finds[T any](params FindsParams) (result FindsResult[T], err error)
func (FindsResult[T]) HasNext ¶ added in v3.1.39
func (r FindsResult[T]) HasNext() bool
func (FindsResult[T]) HasPrev ¶ added in v3.1.40
func (r FindsResult[T]) HasPrev() bool
type GRPCClientConfig ¶ added in v3.1.29
type GRPCClientConfig struct {
TransportCredentials credentials.TransportCredentials
}
GRPCClientConfig 为一个逻辑服务配置 transport credentials。 Core 不解析证书或服务身份,每次建立连接时只使用该凭据的副本。
type GRPCCtx ¶ added in v3.1.50
type GRPCCtx struct {
// contains filtered or unexported fields
}
GRPCCtx is a request-scoped adapter for unary or stream server contexts. It does not change protobuf method signatures or own the context lifetime. Services should continue to accept context.Context, obtained with StdContext.
func NewGRPCCtx ¶ added in v3.1.50
NewGRPCCtx wraps the current RPC context (stream.Context for streams). A nil context has background semantics; response writes still require a server RPC.
func (*GRPCCtx) ClientIP ¶ added in v3.1.50
ClientIP uses ExtractClientInfo's Gateway trust checks, never a raw IP header.
func (*GRPCCtx) Cookie ¶ added in v3.1.50
Cookie reads and URL-decodes an incoming cookie, like BaseCtx.Cookies. Missing cookies return http.ErrNoCookie; malformed URL escapes return an error.
func (*GRPCCtx) GetHeader ¶ added in v3.1.50
GetHeader reads the first incoming metadata value. It is not an identity check.
func (*GRPCCtx) HeaderValues ¶ added in v3.1.50
HeaderValues reads all incoming values and returns an independent copy.
func (*GRPCCtx) OutgoingContext ¶ added in v3.1.50
OutgoingContext returns a derived context for a downstream RPC. Only explicitly supplied metadata is added; existing outgoing keys are replaced by supplied keys. Incoming metadata is never automatically forwarded. Neither source map is mutated or aliased. The original deadline/cancellation and other context values are retained.
func (*GRPCCtx) RemoveCookie ¶ added in v3.1.50
RemoveCookie queues an expired response cookie using the existing removal rules.
func (*GRPCCtx) RequestMetadata ¶ added in v3.1.50
RequestMetadata returns an independent copy of incoming metadata. Editing it affects neither the request nor a response/downstream call.
func (*GRPCCtx) SetCookie ¶ added in v3.1.50
SetCookie queues a response cookie using the existing BaseCtx-compatible defaults.
func (*GRPCCtx) SetHeader ¶ added in v3.1.50
SetHeader queues HTTP response headers through Core's Gateway bridge. Repeated calls append values; this does not modify request or outgoing metadata.
func (*GRPCCtx) StdContext ¶ added in v3.1.50
StdContext preserves the original context, including deadline, cancellation, transport identity and Core's Gateway trust configuration.
type GRPCServerConfig ¶ added in v3.1.28
type GRPCServerConfig struct {
TransportCredentials credentials.TransportCredentials
UnaryInterceptors []grpc.UnaryServerInterceptor
StreamInterceptors []grpc.StreamServerInterceptor
// TrustGateway verifies the RPC caller using peer address or authenticated
// transport identity. Nil trusts private/loopback peer IPs. A configured
// callback fully overrides that fallback. Never trust request metadata here.
TrustGateway func(context.Context) bool
}
GRPCServerConfig 定义 Core 创建 gRPC server 前可注入的通用 transport 与 interceptor。 调用方拥有证书身份和授权策略;Core 只负责 server 生命周期和 interceptor chain。
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 HealthProbe ¶ added in v3.1.30
type HealthProbe func() error
HealthProbe 健康探针函数,返回 nil 表示健康,否则返回错误信息。
type HookWriter ¶
type HookWriter struct {
Writer io.Writer
Monitor *LogMonitor
}
type IModel ¶ added in v3.0.7
type IModel struct {
ID IntID `gorm:"primarykey;autoIncrement:false;comment:主键" json:"id,omitzero"`
CreatedAt *time.Time `gorm:"<-:create;comment:创建时间" json:"created_at,omitempty"`
UpdatedAt *time.Time `gorm:"autoUpdateTime;comment:更新时间" json:"updated_at,omitempty"`
DeletedAt *gorm.DeletedAt `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
type IntMoney
deprecated
type IntMoney int64
Deprecated: IntMoney 已废弃,请使用 coins.Money
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 LogRotateConfig ¶ added in v3.1.19
type LogRotateConfig struct {
MaxSize int64
Daily bool
RetainDays int
Compress bool
CopyTruncate bool
DelayCompress time.Duration
MissingOK bool
NotifEmpty bool
}
func ParseLogRotateConfig ¶ added in v3.1.19
func ParseLogRotateConfig(opts ...string) (LogRotateConfig, error)
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_ALL 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;comment:创建时间"`
UpdatedAt *time.Time `json:"updated_at,omitempty" gorm:"autoUpdateTime;comment:更新时间"`
DeletedAt *gorm.DeletedAt `json:"deleted_at,omitempty" gorm:"index;comment:删除时间"`
}
func (*Models) BeforeCreate ¶
type ModuleInfo ¶
type Money
deprecated
type Money float64
Deprecated: Money 已废弃,请使用 coins.Money
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 NSQConsumer ¶ added in v3.1.17
type NSQConsumer struct {
// contains filtered or unexported fields
}
NSQConsumer 封装 nsq.Consumer
func NewNSQConsumer ¶ added in v3.1.17
func NewNSQConsumer(conf NSQConsumerConfig) (*NSQConsumer, error)
NewNSQConsumer 创建 NSQ Consumer
func (*NSQConsumer) ChangeMaxInFlight ¶ added in v3.1.17
func (nc *NSQConsumer) ChangeMaxInFlight(maxInFlight int)
ChangeMaxInFlight 动态调整最大在途消息数
func (*NSQConsumer) DeliveryPaused ¶ added in v3.1.74
func (nc *NSQConsumer) DeliveryPaused() bool
DeliveryPaused 表示本消费者因投递次数耗尽而暂停;原消息仍保留在 broker。
func (*NSQConsumer) DeliveryState ¶ added in v3.1.74
func (nc *NSQConsumer) DeliveryState() NSQDeliveryState
DeliveryState 返回投递预算与暂停原因,供健康检查和告警读取。
func (*NSQConsumer) IsStarved ¶ added in v3.1.17
func (nc *NSQConsumer) IsStarved() bool
IsStarved 判断消费者是否饥饿(可用于背压)
func (*NSQConsumer) RecoverDelivery ¶ added in v3.1.75
func (nc *NSQConsumer) RecoverDelivery(key string, budget uint32, deadline time.Time) (NSQDeliveryRecovery, error)
RecoverDelivery 仅供已验证的运维入口调用;调用方必须验证当前进程代次及订阅作用域。
func (*NSQConsumer) Start ¶ added in v3.1.17
func (nc *NSQConsumer) Start(handler NSQHandlerFunc) error
Start 启动消费者(阻塞直到 Stop 或连接断开) handler 返回 nil 确认消息,返回 error 重新入队
func (*NSQConsumer) StartAsync ¶ added in v3.1.17
func (nc *NSQConsumer) StartAsync(handler NSQHandlerFunc) error
StartAsync 异步启动消费者
func (*NSQConsumer) Stats ¶ added in v3.1.17
func (nc *NSQConsumer) Stats() *nsq.ConsumerStats
Stats 获取消费者统计
func (*NSQConsumer) Stop ¶ added in v3.1.17
func (nc *NSQConsumer) Stop()
Stop requests asynchronous withdrawal; application cleanup separately waits for both the transport and the real business handlers to finish.
type NSQConsumerBuilder ¶ added in v3.1.17
type NSQConsumerBuilder struct {
// contains filtered or unexported fields
}
NSQConsumerBuilder 消费者构建器
func NewNSQConsumerBuilder ¶ added in v3.1.17
func NewNSQConsumerBuilder(topic, channel string) *NSQConsumerBuilder
NewNSQConsumerBuilder 创建消费者构建器
func (*NSQConsumerBuilder) Build ¶ added in v3.1.17
func (b *NSQConsumerBuilder) Build() (*NSQConsumer, error)
Build 构建 Consumer
func (*NSQConsumerBuilder) BuildAndStart ¶ added in v3.1.17
func (b *NSQConsumerBuilder) BuildAndStart(handler NSQHandlerFunc) (*NSQConsumer, error)
BuildAndStart 构建并启动消费者
func (*NSQConsumerBuilder) WithConcurrency ¶ added in v3.1.17
func (b *NSQConsumerBuilder) WithConcurrency(n int) *NSQConsumerBuilder
WithConcurrency 设置并发数
func (*NSQConsumerBuilder) WithLookupd ¶ added in v3.1.17
func (b *NSQConsumerBuilder) WithLookupd(addrs ...string) *NSQConsumerBuilder
WithLookupd 设置 lookupd 地址
func (*NSQConsumerBuilder) WithMaxAttempts ¶ added in v3.1.17
func (b *NSQConsumerBuilder) WithMaxAttempts(n uint16) *NSQConsumerBuilder
WithMaxAttempts 设置最大重试次数
func (*NSQConsumerBuilder) WithMaxBackoff ¶ added in v3.1.17
func (b *NSQConsumerBuilder) WithMaxBackoff(d time.Duration) *NSQConsumerBuilder
WithMaxBackoff 设置最大退避时间
func (*NSQConsumerBuilder) WithMaxInFlight ¶ added in v3.1.17
func (b *NSQConsumerBuilder) WithMaxInFlight(n int) *NSQConsumerBuilder
WithMaxInFlight 设置最大在途消息数
func (*NSQConsumerBuilder) WithMsgTimeout ¶ added in v3.1.17
func (b *NSQConsumerBuilder) WithMsgTimeout(d time.Duration) *NSQConsumerBuilder
WithMsgTimeout 设置消息处理超时
func (*NSQConsumerBuilder) WithNSQD ¶ added in v3.1.17
func (b *NSQConsumerBuilder) WithNSQD(addrs ...string) *NSQConsumerBuilder
WithNSQD 设置 nsqd 直连地址
type NSQConsumerConfig ¶ added in v3.1.17
type NSQConsumerConfig struct {
AuthSecret string // 非空时显式覆盖,否则继承最近成功 InitNSQ 的认证凭据。
Topic string // Topic 名称(必填)
Channel string // Channel 名称(必填)
NSQDs []string // 直连 nsqd 地址列表(如 ["127.0.0.1:4150"])
Lookupds []string // nsqlookupd 地址列表(如 ["127.0.0.1:4161"])
Concurrency int // 并发处理数(默认 1)
MaxInFlight int // 最大在途消息数(默认 200)
MaxAttempts uint16 // 最大重试次数(默认 5)
DisableMaxAttempts bool // 显式关闭超限自动 FIN,由业务持久化结果决定是否确认。
MaxDeliveryAttempts uint16 // 非零时超限暂停本消费者并保留原消息,禁止自动 FIN。
MaxBackoff time.Duration // 最大退避时间(默认 2m)
MsgTimeout time.Duration // 消息处理超时(0 使用服务端默认)
}
NSQConsumerConfig 消费者配置
type NSQDeliveryRecovery ¶ added in v3.1.75
type NSQDeliveryRecovery struct {
CommandKey string `json:"command_key"`
Budget uint32 `json:"budget"`
Used uint32 `json:"used"`
Deadline time.Time `json:"deadline"`
Active bool `json:"active"`
}
NSQDeliveryRecovery 只记录当前进程的有限恢复授权,不修改 broker 消息身份和次数。
type NSQDeliveryState ¶ added in v3.1.74
type NSQDeliveryState struct {
Topic string `json:"topic"`
Channel string `json:"channel"`
Paused bool `json:"paused"`
Attempts uint16 `json:"attempts"`
Limit uint16 `json:"limit"`
Recovery *NSQDeliveryRecovery `json:"recovery,omitempty"`
}
NSQDeliveryState 提供不含消息正文的投递暂停观测。
type NSQHandlerContext ¶ added in v3.1.17
NSQHandlerContext 带超时的消息处理上下文
func NewNSQHandlerContext ¶ added in v3.1.17
func NewNSQHandlerContext(msg *nsq.Message, timeout time.Duration) *NSQHandlerContext
NewNSQHandlerContext 创建带超时的消息处理上下文
type NSQHandlerFunc ¶ added in v3.1.17
NSQHandlerFunc 消息处理函数 返回 nil → FIN(确认处理完成) 返回 error → REQ(重新入队,自动退避重试)
type NSQProducer ¶ added in v3.1.17
NSQProducer 封装 nsq.Producer
func NewNSQProducer ¶ added in v3.1.17
func NewNSQProducer(addr string, cfg *nsq.Config) (*NSQProducer, error)
NewNSQProducer 创建 Producer
func (*NSQProducer) DeferredPublish ¶ added in v3.1.17
DeferredPublish 延迟发布消息
func (*NSQProducer) DeferredPublishJSON ¶ added in v3.1.17
DeferredPublishJSON 延迟发布 JSON 消息
func (*NSQProducer) MultiPublish ¶ added in v3.1.17
func (p *NSQProducer) MultiPublish(topic string, bodies [][]byte) error
MultiPublish 批量发布消息到同一 topic
func (*NSQProducer) Publish ¶ added in v3.1.17
func (p *NSQProducer) Publish(topic string, body []byte) error
Publish 发布消息
func (*NSQProducer) PublishJSON ¶ added in v3.1.17
func (p *NSQProducer) PublishJSON(topic string, v any) error
PublishJSON 发布 JSON 消息(自动序列化)
func (*NSQProducer) PublishString ¶ added in v3.1.17
func (p *NSQProducer) PublishString(topic, message string) error
PublishString 发布字符串消息
type NextPage ¶ added in v3.1.8
type NextPages ¶
type Options ¶
var (
Conf Options
)
func LoadConfigFile ¶
LoadConfigFile 加载并展开配置;托管身份的相对文件路径以该配置所在目录为基准。
func (Options) ExpandEnv ¶ added in v3.1.30
func (opt Options) ExpandEnv()
ExpandEnv 递归替换所有配置值中的 ${ENV:VAR} 为环境变量值。 支持格式:
- ${ENV:VAR} → os.Getenv("VAR")
- ${ENV:VAR:def} → os.Getenv("VAR") 或默认值 "def"
零开销 — 仅在 LoadConfigFile 启动时调用一次。
func (*Options) GetDuration ¶ added in v3.1.25
func (*Options) GetPathBool ¶ added in v3.1.8
GetPathBool 获取布尔值
func (*Options) GetPathInt ¶ added in v3.1.8
func (*Options) GetPathString ¶ added in v3.1.8
GetPathString 支持通过点号路径获取嵌套配置 例如: GetPathString("telegram.token") 会获取 cfg["telegram"].(Options)["token"]
func (*Options) GetPathStrings ¶ added in v3.1.10
GetPathStrings 获取字符串数组类型的配置值
type Page ¶ added in v3.1.8
type Pages ¶
type RecoveryFunc ¶
RecoveryFunc defines the function passable to CustomRecovery.
type RedisClient ¶ added in v3.1.17
func (*RedisClient) BitCount ¶ added in v3.1.17
func (r *RedisClient) BitCount(ctx context.Context, key string, bitCount *redis.BitCount) (int64, error)
BitCount 统计位为1的数量
func (*RedisClient) Delete ¶ added in v3.1.17
func (r *RedisClient) Delete(ctx context.Context, keys ...string) error
Delete 删除
func (*RedisClient) Eval ¶ added in v3.1.17
func (r *RedisClient) Eval(ctx context.Context, script string, keys []string, args ...any) (any, error)
Eval 执行 Lua 脚本
func (*RedisClient) EvalSha ¶ added in v3.1.17
func (r *RedisClient) EvalSha(ctx context.Context, sha1 string, keys []string, args ...any) (any, error)
EvalSha 执行 Lua 脚本(通过 SHA1)
func (*RedisClient) IncrWithTTL ¶ added in v3.1.17
func (r *RedisClient) IncrWithTTL(ctx context.Context, key string, ttl time.Duration) (int64, error)
IncrWithTTL 递增并设置过期(常用于限流)
func (*RedisClient) NewStreamConsumer ¶ added in v3.1.17
func (r *RedisClient) NewStreamConsumer(conf StreamConsumerConfig) *StreamConsumer
NewStreamConsumer 创建 Stream 消费者
func (*RedisClient) Ping ¶ added in v3.1.17
func (r *RedisClient) Ping(ctx context.Context) error
Ping 检测连接
func (*RedisClient) Pipeline ¶ added in v3.1.17
func (r *RedisClient) Pipeline() redis.Pipeliner
Pipeline 获取管道
func (*RedisClient) Pipelined ¶ added in v3.1.17
func (r *RedisClient) Pipelined(ctx context.Context, fn func(redis.Pipeliner) error) ([]redis.Cmder, error)
Pipelined 执行管道操作
func (*RedisClient) Scan ¶ added in v3.1.17
func (r *RedisClient) Scan(ctx context.Context, cursor uint64, match string, count int64) *redis.ScanCmd
Scan 扫描匹配的 key
func (*RedisClient) ScriptLoad ¶ added in v3.1.17
ScriptLoad 预加载 Lua 脚本
func (*RedisClient) SetJSON ¶ added in v3.1.17
func (r *RedisClient) SetJSON(ctx context.Context, key string, value any, ttl ...time.Duration) error
SetJSON 自动序列化存储
func (*RedisClient) TxPipeline ¶ added in v3.1.17
func (r *RedisClient) TxPipeline() redis.Pipeliner
TxPipeline 获取事务管道
func (*RedisClient) XAdd ¶ added in v3.1.17
func (r *RedisClient) XAdd(ctx context.Context, stream string, fields map[string]any, id ...string) (string, error)
XAdd 向 Stream 添加消息 返回消息 ID
func (*RedisClient) XAddJSON ¶ added in v3.1.17
func (r *RedisClient) XAddJSON(ctx context.Context, stream string, value any, id ...string) (string, error)
XAddJSON 向 Stream 添加 JSON 消息 将 value 序列化为 JSON 存入 _data 字段
func (*RedisClient) XClaim ¶ added in v3.1.17
func (r *RedisClient) XClaim(ctx context.Context, stream, group, consumer string, minIdleTime time.Duration, ids ...string) ([]StreamMessage, error)
XClaim 认领待处理消息(用于故障恢复)
func (*RedisClient) XGroupCreate ¶ added in v3.1.17
func (r *RedisClient) XGroupCreate(ctx context.Context, stream, group, startID string) error
XGroupCreate 创建消费者组 startID: "0" 从头消费, "$" 只消费新消息
func (*RedisClient) XGroupDestroy ¶ added in v3.1.17
func (r *RedisClient) XGroupDestroy(ctx context.Context, stream, group string) error
XGroupDestroy 删除消费者组
func (*RedisClient) XRange ¶ added in v3.1.17
func (r *RedisClient) XRange(ctx context.Context, stream, start, stop string, count ...int64) ([]StreamMessage, error)
XRange 按 ID 范围读取消息
func (*RedisClient) XRead ¶ added in v3.1.17
func (r *RedisClient) XRead(ctx context.Context, stream string, startID string, count ...int64) ([]StreamMessage, error)
XRead 从 Stream 读取消息(非消费者组模式)
func (*RedisClient) XReadGroup ¶ added in v3.1.17
func (r *RedisClient) XReadGroup(ctx context.Context, stream, group, consumer string, count int64, block time.Duration) ([]StreamMessage, error)
XReadGroup 从消费者组读取消息
func (*RedisClient) ZIncrBy ¶ added in v3.1.17
func (r *RedisClient) ZIncrBy(ctx context.Context, key string, increment float64, member string) (float64, error)
ZIncrBy 有序集合成员分数递增
func (*RedisClient) ZRangeByScore ¶ added in v3.1.17
func (r *RedisClient) ZRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)
ZRangeByScore 按分数范围获取有序集合成员
func (*RedisClient) ZRevRangeByScore ¶ added in v3.1.17
func (r *RedisClient) ZRevRangeByScore(ctx context.Context, key string, opt *redis.ZRangeBy) ([]string, error)
ZRevRangeByScore 按分数范围倒序获取有序集合成员
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 RotatingLogWriter ¶ added in v3.1.19
type RotatingLogWriter struct {
// contains filtered or unexported fields
}
func NewRotatingLogWriter ¶ added in v3.1.19
func NewRotatingLogWriter(path string, opts ...string) (*RotatingLogWriter, error)
func NewRotatingLogWriterConfig ¶ added in v3.1.19
func NewRotatingLogWriterConfig(path string, cfg LogRotateConfig) (*RotatingLogWriter, error)
func (*RotatingLogWriter) Close ¶ added in v3.1.19
func (w *RotatingLogWriter) Close() error
func (*RotatingLogWriter) RedirectStdout ¶ added in v3.1.19
func (w *RotatingLogWriter) RedirectStdout() error
type RouteNode ¶
type RouteNode struct {
// contains filtered or unexported fields
}
RouteNode 压缩基数树节点。 每个节点的 path 可跨越多个路径段(如 "api/v1/"),实现 O(k) 前缀匹配。
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
Group(prefix string, handlers ...HandlerFuncs) 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;autoIncrement:false;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 StaticConfig ¶ added in v3.1.61
type StaticConfig struct {
// MaxAge defaults to 7 days when zero; a negative value requests revalidation.
MaxAge time.Duration
// Immutable is only appropriate when changing content also changes its URL.
// HTML always uses no-cache so entry documents can discover new assets.
Immutable bool
}
StaticConfig opts a static mount into browser/CDN caching. Omit the config to retain the original behavior. Existing Cache-Control headers take precedence.
type StreamConsumer ¶ added in v3.1.17
type StreamConsumer struct {
// contains filtered or unexported fields
}
func (*StreamConsumer) Run ¶ added in v3.1.17
func (c *StreamConsumer) Run(ctx context.Context, handler func(ctx context.Context, msg StreamMessage) error) error
Run 启动消费者(阻塞运行,直到 context 取消) handler 返回 nil 自动 ACK,返回 error 不 ACK(进入 pending 列表等待重试)
type StreamConsumerConfig ¶ added in v3.1.17
type StreamConsumerConfig struct {
Stream string // Stream 名称
Group string // 消费者组名称
Consumer string // 消费者名称
Count int64 // 每次读取条数(默认 10)
Block time.Duration // 阻塞等待时间(默认 5s)
ClaimIdle time.Duration // 认领待处理消息的最小空闲时间(默认 30s,0 禁用)
ClaimCount int64 // 每次认领的最大条数(默认 10)
AutoAck bool // 处理成功是否自动 ACK(默认 true)
}
type StreamMessage ¶ added in v3.1.17
type StreamMessage struct {
ID string // 消息 ID (如 "1672531200000-0")
Fields map[string]any // 消息字段
}
StreamMessage 表示一条 Stream 消息
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
¶
- application_resources.go
- auto_http_routes.go
- certificates.go
- config_file_store.go
- config_key.go
- construct.go
- cookie.go
- core.go
- crypto.go
- ctx.go
- dns_provider.go
- etcd_tls.go
- event_hub.go
- group.go
- grpc.go
- grpc_client.go
- grpc_ctx.go
- grpc_receive_limit.go
- grpc_response.go
- handler.go
- logger.go
- model.go
- model_cursor.go
- model_query.go
- module.go
- nsq.go
- nsq_delivery_recovery.go
- options.go
- path.go
- readiness.go
- redis.go
- route.go
- route_node.go
- static_cache.go
- utils.go
- workload.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package certificate 提供由业务授权的精确域名证书管理,不在握手中触发签发。
|
Package certificate 提供由业务授权的精确域名证书管理,不在握手中触发签发。 |
|
cmd
|
|
|
corectl
command
|
|
|
coregen
command
|
|
|
* KV 存储相关方法 提供对etcd KV存储的封装,包括Put、Get等操作
|
* KV 存储相关方法 提供对etcd KV存储的封装,包括Put、Get等操作 |
|
example
|
|
|
grpc-cookie
Package grpccookie provides copyable response scaffolding for gRPC auth handlers.
|
Package grpccookie provides copyable response scaffolding for gRPC auth handlers. |
|
restful
command
|
|
|
standard/cmd
command
|
|
|
standard/internal/app
Package app owns dependency assembly.
|
Package app owns dependency assembly. |
|
standard/internal/domain/user
Package user defines protocol-independent business errors.
|
Package user defines protocol-independent business errors. |
|
standard/internal/models
Code generated by core.
|
Code generated by core. |
|
websocket
command
|
|
|
work
command
|
|
|
internal
|
|
|
grpchttp
Package grpchttp defines the explicit response metadata contract shared by Core gRPC helpers and the HTTP Gateway.
|
Package grpchttp defines the explicit response metadata contract shared by Core gRPC helpers and the HTTP Gateway. |
|
logbridge
Package logbridge lets independent clients use Core's configured logger without importing the application, database, discovery, or server packages.
|
Package logbridge lets independent clients use Core's configured logger without importing the application, database, discovery, or server packages. |
|
responsecompression
Package responsecompression shares streaming response behavior between codecs.
|
Package responsecompression shares streaming response behavior between codecs. |
|
middleware
|
|
|
bodylimit
Package bodylimit 限制请求体大小,防止恶意大 Body 导致 OOM。
|
Package bodylimit 限制请求体大小,防止恶意大 Body 导致 OOM。 |
|
brotli
Package brotli provides opt-in streaming Brotli HTTP response compression.
|
Package brotli provides opt-in streaming Brotli HTTP response compression. |
|
compress
Package compress negotiates zstd, Brotli and gzip response compression.
|
Package compress negotiates zstd, Brotli and gzip response compression. |
|
etag
Package etag provides conditional responses using representation validators.
|
Package etag provides conditional responses using representation validators. |
|
gzip
Package gzip provides opt-in streaming HTTP response compression.
|
Package gzip provides opt-in streaming HTTP response compression. |
|
monitor
Package monitor 提供服务器运行时监控插件,暴露 CPU、内存、文件句柄、连接数等指标。
|
Package monitor 提供服务器运行时监控插件,暴露 CPU、内存、文件句柄、连接数等指标。 |
|
otel
Package otel 提供 OpenTelemetry Trace 上下文传播中间件。
|
Package otel 提供 OpenTelemetry Trace 上下文传播中间件。 |
|
security
Package security 提供安全 HTTP 响应头中间件,设置 HSTS、CSP、X-Content-Type-Options 等。
|
Package security 提供安全 HTTP 响应头中间件,设置 HSTS、CSP、X-Content-Type-Options 等。 |
|
timeout
Package timeout 提供请求超时控制中间件。
|
Package timeout 提供请求超时控制中间件。 |
|
zstd
Package zstd provides opt-in streaming HTTP response compression.
|
Package zstd provides opt-in streaming HTTP response compression. |
|
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: |