Documentation
¶
Overview ¶
grpc.go
Index ¶
- Constants
- Variables
- 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 D(f string, args ...any)
- func DBType(name ...string) string
- 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 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 GrpcHeader(ctx context.Context, key string) string
- func HashPassword(password string) (string, error)
- func HashPasswordWithCost(password string, cost int) (string, error)
- 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 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 RegisterModule(inst module)
- func RemoteIP(h iGet, ip 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) 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) SaveFile(key, dst string, args ...any) (relpath, abspath string, err error)
- func (c *BaseCtx) SaveFiles(key, dst string, args ...any) (rel Array, err error)
- func (c *BaseCtx) Send(buf []byte) error
- func (c *BaseCtx) SendStatus(code int, msg ...string) error
- func (c *BaseCtx) SendString(str ...any) error
- func (c *BaseCtx) Set(key string, val any)
- func (c *BaseCtx) SetCookie(name, value string, exp time.Time, path string, args ...any)
- func (c *BaseCtx) SetHeader(key string, value string)
- func (c *BaseCtx) SetParams(key, val string)
- func (c *BaseCtx) StartAt(t ...time.Time) time.Time
- func (c *BaseCtx) Status(code int) Ctx
- func (c *BaseCtx) Stream(step func(w io.Writer) bool) bool
- func (c *BaseCtx) TextBytes(out io.Writer, f string, bind ...any) error
- func (c *BaseCtx) TextRender(f string, bind ...any) error
- func (c *BaseCtx) ToJSON(data any, msg ...any) error
- func (c *BaseCtx) ToJSONCode(data any, msg ...any) error
- func (c *BaseCtx) Type(extension string, charset ...string) Ctx
- func (c *BaseCtx) Validate(out any) error
- func (c *BaseCtx) Vars() Map
- func (c *BaseCtx) Vary(fields ...string) Ctx
- func (c *BaseCtx) ViewReload()
- func (c *BaseCtx) ViewTheme(theme string)
- func (c *BaseCtx) XML(data any) error
- type 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) 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) ErrGroup() *errgroup.Group
- func (app *Core) GET(path string, handler any, middleware ...any) Router
- 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) 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) 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) RegisterGRPCService(registerFunc func(*grpc.Server))
- func (app *Core) ReleaseCtx(c Ctx)
- func (app *Core) RemoveHandle(methods []string, uri string)
- func (app *Core) Run(port ...any) error
- func (app *Core) Serve(ln net.Listener) error
- func (app *Core) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (app *Core) Static(relativePath, root string) Router
- func (app *Core) StaticFS(relativePath string, fs http.FileSystem) Router
- func (app *Core) StaticFile(relativePath, dirname string) Router
- func (app *Core) StaticFileFS(relativePath, dirname string, fs http.FileSystem) Router
- func (app *Core) TRACE(path string, handler any, middleware ...any) Router
- func (app *Core) Use(fn ...any) Router
- type Ctx
- type DB
- type Date
- type Enum
- type Error
- type ErrorHandler
- type Errors
- type EventData
- type EventHub
- type Group
- func (g *Group) ALL(path string, handler any, middleware ...any) Router
- func (g *Group) Add(methods []string, path string, handler any, middleware ...any) Router
- func (g *Group) CONNECT(path string, handler any, middleware ...any) Router
- func (g *Group) DELETE(path string, handler any, middleware ...any) Router
- func (g *Group) GET(path string, handler any, middleware ...any) Router
- func (g *Group) Group(prefix string, handlers ...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 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) SubInt(in int, fraction ...int) Money
- func (m Money) ToFixed(fraction ...int) Money
- func (m Money) ToFloor(p int) Money
- func (m Money) ToRound(p int) Money
- func (m *Money) UnmarshalBinary(data []byte) error
- func (m *Money) UnmarshalJSON(data []byte) error
- type NSQConsumer
- func (nc *NSQConsumer) ChangeMaxInFlight(maxInFlight int)
- func (nc *NSQConsumer) IsStarved() bool
- 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 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) GetAs(k string, v any) error
- func (opt *Options) GetBool(k string, def ...bool) bool
- func (opt *Options) GetInt(k string, def ...int) int
- func (opt *Options) GetInt64(k string, def ...int64) int64
- func (opt *Options) GetMap(k string, def ...Options) Options
- func (opt *Options) 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 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 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 ( 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 (
ErrInvalidValidationType = NewError(400, "验证类型必须是结构体指针")
)
全局验证器实例 自定义错误类型
var (
Methods = []string{
"GET",
"POST",
"HEAD",
"PUT",
"DELETE",
"OPTIONS",
"CONNECT",
"TRACE",
"PATCH",
"ALL",
"USE",
}
)
var UuidNil = UUID{uuid.Nil}
Functions ¶
func CheckPassword ¶ added in v3.1.16
CheckPassword 验证密码
func Contains ¶
func Contains[S ~[]E, E comparable](s S, v E) bool
func ContainsAny ¶
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 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
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 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 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 RegisterModule ¶
func RegisterModule(inst module)
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) RedirectJS ¶
func (*BaseCtx) RemoteIP ¶
RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port). It also checks if the remoteIP is a trusted proxy or not. In order to perform this validation, it will see if the IP is contained within at least one of the CIDR blocks
func (*BaseCtx) RemoveCookie ¶
func (*BaseCtx) Response ¶
func (c *BaseCtx) Response() ResponseWriter
ResponseWriter implements Ctx.
func (*BaseCtx) SaveFile ¶
SaveFile upload file save to a folder
path = {root}/{dst}/{id}
@param
name string filename
dst string dst path
root string root path optional
id path optional type uid.UID, int, uint, int64,uint64
rename bool optional
return relPath, absPath
c.SaveFile("file", "/images")
(string) relpath "/images/10/favicon.png"
(string) abspath "/images/10/favicon.png"
c.SaveFile("file", "/images", "./static")
(string) relpath "/images/10/5hsbkthaadld/favicon.png"
(string) abspath "/static/images/10/5hsbkthaadld/favicon.png"
c.SaveFile("file", "/images", "./static", uid.New())
(string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
(string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"
👇file 👇dst 👇root 👇id 👇rename
c.SaveFile("file", "/images", "./static", uid.New(), true)
(string) relpath "/images/10/5hsbkthaadld/5hsbkthaadld.png"
(string) abspath "/static/images/10/5hsbkthaadld/5hsbkthaadld.png"
func (*BaseCtx) SaveFiles ¶
SaveFiles like SaveFile
@params key string MultipartForm key name : files dst string static to ./static more args see SaveFile
rel, err := c.SaveFiles("files", "static", true)
return relative url path rel is
return []string {
"/static/09/wjejwifx.jpg",
"/static/09/wjejwifx.jpg",
"/static/09/wjejwifx.jpg",
}
func (*BaseCtx) SendString ¶
func (*BaseCtx) SetCookie ¶
SetCookie adds a Set-Cookie header to the ResponseWriter's headers. The provided cookie must have a valid Name. Invalid cookies may be silently dropped.
func (*BaseCtx) Stream ¶
Stream sends a streaming response and returns a boolean indicates "Is client disconnected in middle of stream"
func (*BaseCtx) Type ¶
Type sets the Content-Type HTTP header to the MIME type specified by the file extension.
func (*BaseCtx) Vary ¶
Vary add the given header field to the vary response header
c.Vary("Accept-Encoding", "Accept", "X-Requested-With")
Response Header:
Vary: Accept-Encoding, Accept, X-Requested-With
func (*BaseCtx) ViewReload ¶
func (c *BaseCtx) ViewReload()
type 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
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) 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) 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) MustGrpcClient ¶ added in v3.1.13
func (app *Core) MustGrpcClient(serviceName string, opts ...grpc.DialOption) *grpc.ClientConn
MustGrpcClient 创建 gRPC 客户端连接,失败则 panic
func (*Core) ProcessedHandler ¶ added in v3.1.11
func (app *Core) ProcessedHandler(hand any) HandlerFuncs
func (*Core) RegisterGRPCService ¶ added in v3.1.10
RegisterGRPCService 注册 gRPC 服务
func (*Core) ReleaseCtx ¶
func (*Core) RemoveHandle ¶ added in v3.1.17
func (*Core) StaticFileFS ¶
func (app *Core) StaticFileFS(relativePath, dirname string, fs http.FileSystem) Router
StaticFileFS works just like `StaticFile` but a custom `http.FileSystem` can be used instead..
app.StaticFileFS("favicon.ico", "./resources/favicon.ico", Dir{".", false})
type Ctx ¶
type Ctx interface {
Context() context.Context // Request().Context()
Ctx() context.Context
Host() string
Response() ResponseWriter // Response() return http.ResponseWriter
Request() *http.Request // Request() return *http.Request
RedirectJS(to string, msg ...string) // use js redirect
Redirect(to string, stCode ...int) 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
Render(f string, bind ...any) error
TextBytes(out io.Writer, f string, bind ...any) error
TextRender(f string, bind ...any) error
SetParams(key string, val string)
// contains filtered or unexported methods
}
type Error ¶
type Error struct {
// contains filtered or unexported fields
}
func (*Error) GRPCStatus ¶ added in v3.1.16
GRPCStatus 实现 gRPC 状态接口,让 status.FromError 能正常工作
type ErrorHandler ¶
type EventHub ¶
type EventHub struct {
// contains filtered or unexported fields
}
func NewEventHub ¶
func (*EventHub) UnRegister ¶
type Group ¶
func (*Group) GET ¶
Get registers a route for GET methods that requests a representation of the specified resource. Requests using GET should only retrieve data.
func (*Group) Use ¶
Use registers a middleware route that will match requests with the provided prefix (which is optional and defaults to "/"). Also, you can pass another app instance as a sub-router along a routing path. It's very useful to split up a large API as many independent routers and compose them as a single service using Use. The core error handler and any of the core sub apps are added to the application's error handlers to be invoked on errors that happen within the prefix route.
app.Use(func(c core.Ctx) error {
return c.Next()
})
app.Use("/api", func(c core.Ctx) error {
return c.Next()
})
app.Use("/api", handler, func(c core.Ctx) error {
return c.Next()
})
subApp := core.New()
app.Use("/mounted-path", subApp)
This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...
type Handler ¶
type Handler struct {
Handlers map[string]any // record callable handle
ID string
// contains filtered or unexported fields
}
func (*Handler) PushHandler ¶
type HandlerFun ¶
type HandlerFun = func(Ctx)
type HandlerFunc ¶
func CustomRecoveryWithWriter ¶
func CustomRecoveryWithWriter(out io.Writer, handle RecoveryFunc) HandlerFunc
CustomRecoveryWithWriter returns a middleware for a given writer that recovers from any panics and calls the provided handle func to handle it.
func Logger ¶
func Logger(conf ...LoggerConfig) HandlerFunc
func Recovery ¶
func Recovery() HandlerFunc
Recovery returns a middleware that recovers from any panics and writes a 500 if there was one.
func RecoveryWithWriter ¶
func RecoveryWithWriter(out io.Writer, recovery ...RecoveryFunc) HandlerFunc
RecoveryWithWriter returns a middleware for a given writer that recovers from any panics and writes a 500 if there was one.
type HandlerFuncs ¶
type HandlerFuncs []HandlerFunc
type HandlerNormal ¶
type HandlerNormal = func(w http.ResponseWriter, r *http.Request)
type HookWriter ¶
type HookWriter struct {
Writer io.Writer
Monitor *LogMonitor
}
type 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) IsStarved ¶ added in v3.1.17
func (nc *NSQConsumer) IsStarved() bool
IsStarved 判断消费者是否饥饿(可用于背压)
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 获取消费者统计
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 {
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)
MaxBackoff time.Duration // 最大退避时间(默认 2m)
MsgTimeout time.Duration // 消息处理超时(0 使用服务端默认)
}
NSQConsumerConfig 消费者配置
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 ¶
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 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 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
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
corectl
command
|
|
|
coregen
command
|
|
|
* KV 存储相关方法 提供对etcd KV存储的封装,包括Put、Get等操作
|
* KV 存储相关方法 提供对etcd KV存储的封装,包括Put、Get等操作 |
|
example
|
|
|
restful
command
|
|
|
websocket
command
|
|
|
work
command
|
|
|
middleware
|
|
|
Package reuseport provides TCP net.Listener with SO_REUSEPORT support.
|
Package reuseport provides TCP net.Listener with SO_REUSEPORT support. |
|
Package tcplisten provides customizable TCP net.Listener with various performance-related options:
|
Package tcplisten provides customizable TCP net.Listener with various performance-related options: |