Documentation ¶
Index ¶
- Constants
- Variables
- func AddHeaders(req *http.Request, headers map[string][]string)
- func AddHealthIndicator(hi HealthIndicator)
- func AddMySQLBootstrapCallback(cbk MySQLBootstrapCallback)
- func AddPropagationKey(key string)
- func AddPropagationKeys(keys ...string)
- func AddRabbitListener(listener RabbitListener)
- func AddShutdownHook(hook func())
- func AppendableFile(name string) (*os.File, error)
- func ArgKeyVal(args []string) map[string][]string
- func BearerAuth(delegate http.Handler, getExpectedToken func() string) http.HandlerFunc
- func BootstrapServer(args []string)
- func BuildRollingLogFileWriter(p NewRollingLogFileParam) *lumberjack.Logger
- func ChainValidationError(parentField string, e error) error
- func ClientSkipTlsSecureCheck()
- func CollectFields(ptr any) []reflect.StructField
- func CollectTypeFields(eleType reflect.Type) []reflect.StructField
- func ConfigureLogging(rail Rail) error
- func ConsulBootstrap(rail Rail) error
- func ConsulBootstrapCondition(rail Rail) (bool, error)
- func ContainsProp(prop string) bool
- func CopyFilter[T any](l []T, f func(T) bool) []T
- func CustomFormatter() logrus.Formatter
- func Debug(args ...interface{})
- func DebugTimeOp(r Rail, start time.Time, name string)
- func Debugf(format string, args ...interface{})
- func DeclareRabbitBinding(ch *amqp.Channel, bind BindingRegistration) error
- func DeclareRabbitExchange(ch *amqp.Channel, exchange ExchangeRegistration) error
- func DeclareRabbitQueue(ch *amqp.Channel, queue QueueRegistration) error
- func DecodeJson(reader io.Reader, ptr any) error
- func DefaultHealthCheck(ctx *gin.Context)
- func DefaultMetricDesc(matcher *regexp.Regexp) []metrics.Description
- func DefaultReadConfig(args []string, rail Rail)
- func DefaultRecovery(c *gin.Context, e interface{})
- func DeregisterConsulService() error
- func DispatchErrMsgJson(c *gin.Context, msg string)
- func DispatchJson(c *gin.Context, body interface{})
- func DispatchJsonCode(c *gin.Context, code int, body interface{})
- func Distinct(l []string) []string
- func DistriTaskBootstrap(rail Rail) error
- func ERand(len int) string
- func EnableBasicAuth(f func(username string, password string, url string, method string) bool)
- func EncodeJson(writer io.Writer, body any) error
- func Error(args ...interface{})
- func Errorf(format string, args ...interface{})
- func ExtractArgValue(args []string, predicate Predicate[string]) string
- func FastDistinct(l []string) []string
- func Fatal(args ...interface{})
- func Fatalf(format string, args ...interface{})
- func FileExists(path string) (bool, error)
- func Filter[T any](l []T, f func(T) bool) []T
- func FilterMetricDesc(nameFilter func(name string) bool, ...) []metrics.Description
- func FuncName(f any) string
- func FuzzParseTime(formats []string, value string) (time.Time, error)
- func GenId() (id string)
- func GenIdP(prefix string) (id string)
- func GenNo(prefix string) string
- func GenNoL(prefix string, len int) string
- func GetConfIntSlice(prop string) []int
- func GetConsulClient() *api.Client
- func GetCtxInt(ctx context.Context, key string) (int, bool)
- func GetCtxStr(ctx context.Context, key string) (string, bool)
- func GetEnv(key string) string
- func GetEnvElse(key string, defVal string) string
- func GetLocalIPV4() string
- func GetMySQL() *gorm.DB
- func GetPropBool(prop string) bool
- func GetPropDur(prop string, unit time.Duration) time.Duration
- func GetPropInt(prop string) int
- func GetPropIntSlice(prop string) []int
- func GetPropStr(prop string) string
- func GetPropStrMap(prop string) map[string]string
- func GetPropStrSlice(prop string) []string
- func GetPropagationKeys() []string
- func GetRedis() *redis.Client
- func GetSqlite() *gorm.DB
- func GetStr(key string) (string, error)
- func GuessConfigFilePath(args []string) string
- func HandleEndpointResult(inb Inbound, rail Rail, result any, err error)
- func HasPrefixIgnoreCase(s string, prefix string) bool
- func HasProp(prop string) bool
- func HasScheduledJobs() bool
- func HasSuffixIgnoreCase(s string, suffix string) bool
- func Info(args ...interface{})
- func Infof(format string, args ...interface{})
- func InitConsulClient() error
- func InitMySQL(rail Rail, p MySQLConnParam) error
- func InitMySQLFromProp(rail Rail) error
- func InitRedis(rail Rail, p RedisConnParam) (*redis.Client, error)
- func InitRedisFromProp(rail Rail) (*redis.Client, error)
- func IsBlankStr(s string) bool
- func IsBool(boolStr string) bool
- func IsConsulClientInitialized() bool
- func IsConsulServiceRegistered() bool
- func IsDebugLevel() bool
- func IsFieldExposed(fieldName string) bool
- func IsLocalAddress(address string) bool
- func IsMySQLInitialized() bool
- func IsMySqlEnabled() bool
- func IsNoneErr(err error) bool
- func IsProdMode() bool
- func IsRLockNotObtainedErr(err error) bool
- func IsRedisClientInitialized() bool
- func IsRedisEnabled() bool
- func IsShuttingDown() bool
- func IsTaskMaster(rail Rail) bool
- func IsTaskSchedulingDisabled() bool
- func IsTrue(boolStr string) bool
- func IsVoid(t reflect.Type) bool
- func JoinQueryParam(queryParams map[string][]string) string
- func JwtEncode(claims jwt.MapClaims, exp time.Duration) (string, error)
- func LTimeOp(start time.Time, name string)
- func LoadConfigFromFile(configFile string, r Rail) error
- func LoadConfigFromReader(reader io.Reader, r Rail) error
- func LoadPrivKey(content string) (*rsa.PrivateKey, error)
- func LoadPropagationKeys(r Rail)
- func LoadPubKey(content string) (*rsa.PublicKey, error)
- func LowercaseNamingStrategy(name string) string
- func ManualBootstrapPrometheus()
- func ManualPprofRegister()
- func MapFirst[K comparable, V any](m *map[K]*V) *V
- func MapKeys[T comparable, V any](m *map[T]V) []T
- func MapValues[K comparable, V any](m *map[K]V) []V
- func MarkServerShuttingDown()
- func MaxInt(a int, b int) int
- func MaxLenStr(s string, max int) string
- func MergeStrPairs(p ...StrPair) map[string][]any
- func MinInt(a int, b int) int
- func MkdirAll(path string) error
- func MkdirParentAll(path string) error
- func MustBind(rail Rail, c *gin.Context, ptr any)
- func MustCompile(fs embed.FS, s string) *template.Template
- func MySQLBootstrap(rail Rail) error
- func MySQLBootstrapCondition(rail Rail) (bool, error)
- func NewDeleteRequest(url string) (*http.Request, error)
- func NewEventBus(name string)
- func NewGetRequest(url string) (*http.Request, error)
- func NewHeadRequest(url string) (*http.Request, error)
- func NewMySQLConn(rail Rail, p MySQLConnParam) (*gorm.DB, error)
- func NewOptionsRequest(url string) (*http.Request, error)
- func NewPostRequest(url string, body io.Reader) (*http.Request, error)
- func NewPromCounter(name string) prometheus.Counter
- func NewPromHisto(name string) prometheus.Histogram
- func NewPromHistoVec(name string, labels []string) *prometheus.HistogramVec
- func NewPutRequest(url string, body io.Reader) (*http.Request, error)
- func NewRabbitChan() (*amqp.Channel, error)
- func NewSubmitAsyncFunc[T any](pool *AsyncPool) func(task func() (T, error)) Future[T]
- func NewVar[T any]() T
- func ObtainRLocker() *redislock.Client
- func OpenFile(name string, flag int) (*os.File, error)
- func PTimeOp(start time.Time, name string)
- func PadNum(n int, digit int) string
- func ParseBearer(authorization string) (string, bool)
- func ParseJson(body []byte, ptr any) error
- func ParseLogLevel(logLevel string) (logrus.Level, bool)
- func PerfLogExclPath(path string)
- func PerfMiddleware() gin.HandlerFunc
- func Pick(set []rune) rune
- func PostJobExec(hook PostJobHook)
- func PostJson(url string, json string) (*http.Response, error)
- func PostServerBootstrapped(callback func(rail Rail) error)
- func PreConfiguredFormatter() logrus.Formatter
- func PreJobExec(hook PreJobHook)
- func PreProcessGin(preProcessor GinPreProcessor)
- func PreServerBootstrap(callback func(rail Rail) error)
- func PrepareWebStaticFs(fs embed.FS, dir string)
- func Printlnf(pat string, args ...any)
- func PrometheusBootstrap(rail Rail) error
- func PrometheusBootstrapCondition(rail Rail) (bool, error)
- func PrometheusHandler() http.Handler
- func PubEventBus(rail Rail, eventObject any, name string) error
- func PublishJson(c Rail, obj any, exchange string, routingKey string) error
- func PublishMsg(c Rail, msg []byte, exchange string, routingKey string, contentType string, ...) error
- func PublishText(c Rail, msg string, exchange string, routingKey string) error
- func RLockExec(ec Rail, key string, runnable Runnable) error
- func RLockRun[T any](rail Rail, key string, runnable LRunnable[T]) (T, error)
- func RabbitBootstrap(rail Rail) error
- func RabbitBootstrapCondition(rail Rail) (bool, error)
- func RabbitConnected() bool
- func RabbitDisconnect(rail Rail) error
- func RabbitMQEnabled() bool
- func RandAlpha(n int) string
- func RandLowerAlpha(n int) string
- func RandLowerAlphaNumeric(n int) string
- func RandLowerAlphaNumeric16() string
- func RandNum(n int) string
- func RandStr(n int) string
- func RandUpperAlpha(n int) string
- func RandUpperAlphaNumeric(n int) string
- func RawAny(url string, handler RawTRouteHandler, extra ...StrPair)
- func ReadFileAll(path string) ([]byte, error)
- func ReadWriteFile(name string) (*os.File, error)
- func RedisBootstrap(rail Rail) error
- func RedisBootstrapCondition(rail Rail) (bool, error)
- func RegisterBootstrapCallback(bootstrapComponent ComponentBootstrap)
- func RegisterConsulService() error
- func RegisterRabbitBinding(b BindingRegistration)
- func RegisterRabbitExchange(e ExchangeRegistration)
- func RegisterRabbitQueue(q QueueRegistration)
- func ResolveArg(arg string) string
- func ResolveServerHost(address string) string
- func SWriteJson(body any) (string, error)
- func ScheduleCron(job Job) error
- func ScheduleDistributedTask(t Job) error
- func SchedulerBootstrap(rail Rail) error
- func SendGet(url string, headers map[string][]string) (*http.Response, error)
- func SendPost(url string, body io.Reader) (*http.Response, error)
- func ServeStatic(inb *Inbound, fs embed.FS, file string)
- func ServeTempl(inb *Inbound, fs embed.FS, tmplName string, data any)
- func SetDefProp(prop string, defVal any)
- func SetDefaultTimeout(ttl time.Duration)
- func SetEnv(key string, val string)
- func SetLogLevel(level string)
- func SetMachineCode(code int) error
- func SetProp(prop string, val any)
- func SetResultBodyBuilder(rbb ResultBodyBuilder) error
- func SetScheduleGroup(groupName string)
- func SetToSlice[T comparable](s Set[T]) []T
- func ShuffleRunes(letters []rune, times int) []rune
- func ShuffleStr(letters string, times int) string
- func Shutdown()
- func SliceGetOne[T any](items []*T) *T
- func Spaces(count int) string
- func SprintMemStats(ms runtime.MemStats) string
- func SqliteBootstrap(rail Rail) error
- func SqliteBootstrapCondition(rail Rail) (bool, error)
- func StartRabbitMqClient(rail Rail) error
- func StartSchedulerAsync()
- func StartSchedulerBlocking()
- func StartTaskSchedulerAsync(rail Rail) error
- func StartTaskSchedulerBlocking(rail Rail) error
- func StopScheduler()
- func StopTaskScheduler()
- func StrMap[T any, V any](l []T, keyMapper func(T) string, valueMapper func(T) V) map[string]V
- func SubEventBus[T any](name string, concurrency int, listener func(rail Rail, t T) error)
- func SubscribeServerChanges(rail Rail, name string, cbk func()) error
- func TermOpenUrl(url string) error
- func TimeOp(r Rail, start time.Time, name string)
- func ToStr(v any) string
- func TraceLogger(ctx context.Context) *logrus.Entry
- func TraceMiddleware() gin.HandlerFunc
- func TraceRequest(ctx context.Context, req *http.Request) *http.Request
- func Tracef(format string, args ...interface{})
- func TypeName(t reflect.Type) string
- func UnmarshalFromProp(ptr any)
- func UnmarshalFromPropKey(key string, ptr any)
- func UnsafeByt2Str(b []byte) string
- func UnsafeStr2Byt(s string) (b []byte)
- func UsePropagationKeys(forEach func(key string))
- func Validate(target any) error
- func ValidateIntRule(ival int64, rule string, fname string, param string) error
- func ValidateIssuer() jwt.ParserOption
- func ValidateRule(field reflect.StructField, value reflect.Value, rule string, ruleParam string) error
- func WalkTagShallow(ptr any, callbacks ...WalkTagCallback) error
- func Warn(args ...interface{})
- func Warnf(format string, args ...interface{})
- func WebServerBootstrap(rail Rail) error
- func WebServerBootstrapCondition(rail Rail) (bool, error)
- func WriteJson(body any) ([]byte, error)
- type AsyncPool
- type AwaitFutures
- type BindingRegistration
- type CTFormatter
- type ComponentBootstrap
- type ConsulApiImpl
- func (c ConsulApiImpl) CatalogFetchServiceNames(rail Rail) (map[string][]string, error)
- func (c ConsulApiImpl) CatalogFetchServiceNodes(rail Rail, name string) ([]*api.CatalogService, error)
- func (c ConsulApiImpl) DeregisterService(serviceId string) error
- func (c ConsulApiImpl) RegisterService(registration *api.AgentServiceRegistration) error
- type ConsulServerList
- func (s *ConsulServerList) IsSubscribed(rail Rail, service string) bool
- func (s *ConsulServerList) ListServers(rail Rail, name string) []Server
- func (s *ConsulServerList) PollInstance(rail Rail, name string) error
- func (s *ConsulServerList) PollInstances(rail Rail) error
- func (s *ConsulServerList) Subscribe(rail Rail, service string) error
- func (s *ConsulServerList) Unsubscribe(rail Rail, service string) error
- func (s *ConsulServerList) UnsubscribeAll(rail Rail) error
- type Consumer
- type Converter
- type ETime
- func (t ETime) FormatClassic() string
- func (t ETime) FormatClassicLocale() string
- func (t ETime) MarshalJSON() ([]byte, error)
- func (et *ETime) Scan(value interface{}) error
- func (t ETime) String() string
- func (t ETime) ToTime() time.Time
- func (t ETime) UnixMilli() int64
- func (t *ETime) UnmarshalJSON(b []byte) error
- func (et ETime) Value() (driver.Value, error)
- type EventPipeline
- type ExchangeRegistration
- type ForEachField
- type Future
- type GinPreProcessor
- type GnResp
- type HardcodedServiceRegistry
- type HealthIndicator
- type HealthStatus
- type HistTimer
- type HttpRoute
- type HttpRouteDoc
- type Inbound
- func (i *Inbound) AddHeader(k string, v string)
- func (i *Inbound) Engine() any
- func (i *Inbound) HandleResult(result any, err error)
- func (i *Inbound) Header(k string) string
- func (i *Inbound) Query(k string) string
- func (i *Inbound) Rail() Rail
- func (i *Inbound) SetHeader(k string, v string)
- func (i *Inbound) Status(status int)
- func (i *Inbound) Unwrap() (http.ResponseWriter, *http.Request)
- type Introspector
- func (it *Introspector) Field(fieldName string) (field reflect.StructField, isFieldFound bool)
- func (it *Introspector) FieldAt(idx int) (field reflect.StructField)
- func (it *Introspector) FieldIdx(fieldName string) (index int, isFieldFound bool)
- func (it *Introspector) IterFields(forEach ForEachField)
- func (it *Introspector) Tag(fieldName string, tagName string) (tag string, isFieldFound bool)
- func (it *Introspector) TagRetriever(fieldName string) (t TagRetriever, isFieldFound bool)
- type Job
- type JobExecStats
- type JobInf
- type JsonMsgListener
- type JsonSerializer
- type LRunnable
- type LazyRouteDecl
- func Delete[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecl
- func Get[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecl
- func IDelete[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecl
- func IGet[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecl
- func IPost[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecl
- func IPut[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecl
- func NewLazyRouteDecl(url string, method string, handler func(c *gin.Context)) *LazyRouteDecl
- func Post[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecl
- func Put[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecl
- func RawDelete(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawGet(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawPost(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawPut(url string, handler RawTRouteHandler) *LazyRouteDecl
- func (g *LazyRouteDecl) Desc(desc string) *LazyRouteDecl
- func (g *LazyRouteDecl) DocHeader(headerName string, desc string) *LazyRouteDecl
- func (g *LazyRouteDecl) DocHeaderReq(v any) *LazyRouteDecl
- func (g *LazyRouteDecl) DocJsonReq(v any) *LazyRouteDecl
- func (g *LazyRouteDecl) DocJsonResp(v any) *LazyRouteDecl
- func (g *LazyRouteDecl) DocQueryParam(queryName string, desc string) *LazyRouteDecl
- func (g *LazyRouteDecl) DocQueryReq(v any) *LazyRouteDecl
- func (g *LazyRouteDecl) Extra(key string, value any) *LazyRouteDecl
- func (g *LazyRouteDecl) Prepend(baseUrl string)
- func (g *LazyRouteDecl) Protected() *LazyRouteDecl
- func (g *LazyRouteDecl) Public() *LazyRouteDecl
- func (g *LazyRouteDecl) Resource(resource string) *LazyRouteDecl
- type LocalCache
- type MappedTRouteHandler
- type MetricsCollector
- type MisoErr
- type MsgListener
- type MySQLBootstrapCallback
- type MySQLConnParam
- type NewRollingLogFileParam
- type Opt
- type OrderedShutdownHook
- type PageQueryBuilder
- type PageRes
- type Paging
- type Pair
- type ParamDoc
- type ParsedJwt
- type Peek
- type PostJobHook
- type PreJobHook
- type Predicate
- type PropagationKeys
- type QueryPageParam
- func (q *QueryPageParam[V]) Exec(rail Rail, tx *gorm.DB) (PageRes[V], error)
- func (q *QueryPageParam[V]) ForEach(t Transform[V]) *QueryPageParam[V]
- func (q *QueryPageParam[V]) WithBaseQuery(qry PageQueryBuilder) *QueryPageParam[V]
- func (q *QueryPageParam[V]) WithPage(p Paging) *QueryPageParam[V]
- func (q *QueryPageParam[V]) WithSelectQuery(qry PageQueryBuilder) *QueryPageParam[V]
- type QueueRegistration
- type RCache
- func (r *RCache[T]) Del(rail Rail, key string) error
- func (r *RCache[T]) DelAll(rail Rail) error
- func (r *RCache[T]) Exists(rail Rail, key string) (bool, error)
- func (r *RCache[T]) Get(rail Rail, key string, supplier func() (T, error)) (T, error)
- func (r *RCache[T]) Put(rail Rail, key string, t T) error
- type RCacheConfig
- type RLock
- type RLockConfig
- type RString
- type RWMap
- type RabbitListener
- type Rail
- func (r Rail) Context() context.Context
- func (r Rail) CtxValInt(key string) int
- func (r Rail) CtxValStr(key string) string
- func (r Rail) CtxValue(key string) any
- func (r Rail) Debug(args ...interface{})
- func (r Rail) Debugf(format string, args ...interface{})
- func (r Rail) Debugln(args ...interface{})
- func (r Rail) Error(args ...interface{})
- func (r Rail) Errorf(format string, args ...interface{})
- func (r Rail) Errorln(args ...interface{})
- func (r Rail) Fatal(args ...interface{})
- func (r Rail) Fatalf(format string, args ...interface{})
- func (r Rail) Fatalln(args ...interface{})
- func (r Rail) Info(args ...interface{})
- func (r Rail) Infof(format string, args ...interface{})
- func (r Rail) Infoln(args ...interface{})
- func (r Rail) NextSpan() Rail
- func (r Rail) Panic(args ...interface{})
- func (r Rail) Panicf(format string, args ...interface{})
- func (r Rail) Panicln(args ...interface{})
- func (r Rail) Print(args ...interface{})
- func (r Rail) Printf(format string, args ...interface{})
- func (r Rail) Println(args ...interface{})
- func (r Rail) SpanId() string
- func (r Rail) TraceId() string
- func (r Rail) Tracef(format string, args ...interface{})
- func (r Rail) Warn(args ...interface{})
- func (r Rail) Warnf(format string, args ...interface{})
- func (r Rail) Warnln(args ...interface{})
- func (r Rail) WithCancel() (Rail, context.CancelFunc)
- func (r Rail) WithCtxVal(key string, val any) Rail
- type RawTRouteHandler
- type RedisConnParam
- type Resp
- type RespUnwrapper
- type ResultBodyBuilder
- type RoutingGroup
- type Runnable
- type SLPinter
- type Serializer
- type Server
- type ServerChangeListenerMap
- type ServerList
- type ServerListServiceRegistry
- type ServerSelector
- type ServiceRegistry
- type Set
- type StrPair
- type Supplier
- type TBucket
- type TClient
- func (t *TClient) AddHeader(k string, v string) *TClient
- func (t *TClient) AddHeaders(headers map[string]string) *TClient
- func (t *TClient) AddQueryParams(k string, v ...string) *TClient
- func (t *TClient) Delete() *TResponse
- func (t *TClient) EnableServiceDiscovery(serviceName string) *TClient
- func (t *TClient) EnableTracing() *TClient
- func (t *TClient) Get() *TResponse
- func (t *TClient) Head() *TResponse
- func (t *TClient) Http() *TClient
- func (t *TClient) Https() *TClient
- func (t *TClient) Options() *TResponse
- func (t *TClient) Post(body io.Reader) *TResponse
- func (t *TClient) PostBytes(body []byte) *TResponse
- func (t *TClient) PostForm(data url.Values) *TResponse
- func (t *TClient) PostJson(body any) *TResponse
- func (t *TClient) Put(body io.Reader) *TResponse
- func (t *TClient) PutBytes(body []byte) *TResponse
- func (t *TClient) PutJson(body any) *TResponse
- func (t *TClient) Require2xx() *TClient
- func (t *TClient) SetContentType(ct string) *TClient
- func (t *TClient) SetHeaders(k string, v ...string) *TClient
- func (t *TClient) UseClient(client *http.Client) *TClient
- type TResponse
- type TRouteHandler
- type TTLCache
- type TagRetriever
- type TickRunner
- type Transform
- type TreePath
- type ValidationError
- type VecTimer
- type Void
- type WalkTagCallback
Constants ¶
const ( BusRoutingKey = "#" BusExchangeKind = "direct" )
const ( // Service registration status - passing. ConsulStatusPassing = "passing" // Zero value for empty serviceId ServiceIdNil = "nil" )
const ( ServiceStatusUp = "UP" ServiceStatusDown = "DOWN" )
const ( LOOPBACK_LOCALHOST = "localhost" LOOPBACK_127 = "127.0.0.1" LOCAL_IP_ANY = "0.0.0.0" )
const ( // whether production mode is turned on (true/false) PropProdMode = "mode.production" /* ------------------------------------ Prop for App ------------------------------------ */ PropAppName = "app.name" /* ------------------------------------ Prop for Consul ------------------------------------ */ PropConsulEnabled = "consul.enabled" PropConsuleRegisterName = "consul.registerName" PropConsulRegisterAddress = "consul.registerAddress" PropConsulAddress = "consul.consulAddress" PropConsulHealthcheckUrl = "consul.healthCheckUrl" PropConsulHealthCheckInterval = "consul.healthCheckInterval" PropConsulHealthcheckTimeout = "consul.healthCheckTimeout" PropConsulHealthCheckFailedDeregAfter = "consul.healthCheckFailedDeregisterAfter" PropConsulRegisterDefaultHealthcheck = "consul.registerDefaultHealthCheck" PropConsulFetchServerInterval = "consul.fetchServerInterval" PropConsulDeregisterUrl = "consul.deregisterUrl" PropConsulEnableDeregisterUrl = "consul.enableDeregisterUrl" PropConsulMetadata = "consul.metadata" /* ------------------------------------ Prop for ServiceDiscovery ------------------------------------ */ PropSDSubscrbe = "service-discovery.subscribe" /* ------------------------------------ Prop for Redis ------------------------------------ */ PropRedisEnabled = "redis.enabled" PropRedisAddress = "redis.address" PropRedisPort = "redis.port" PropRedisUsername = "redis.username" PropRedisPassword = "redis.password" PropRedisDatabase = "redis.database" /* ------------------------------------ Prop for MySQL ------------------------------------ */ PropMySQLEnabled = "mysql.enabled" PropMySQLUser = "mysql.user" PropMySQLPassword = "mysql.password" PropMySQLSchema = "mysql.database" PropMySQLHost = "mysql.host" PropMySQLPort = "mysql.port" PropMySQLConnParam = "mysql.connection.parameters" PropMySQLConnLifetime = "mysql.connection.lifetime" PropMySQLMaxOpenConns = "mysql.connection.open.max" PropMySQLMaxIdleConns = "mysql.connection.idle.max" PropServerEnabled = "server.enabled" PropServerHost = "server.host" PropServerPort = "server.port" PropServerGracefulShutdownTimeSec = "server.gracefulShutdownTimeSec" PropServerPerfEnabled = "server.perf.enabled" PropServerRequestLogEnabled = "server.request-log.enabled" PropServerPropagateInboundTrace = "server.trace.inbound.propagate" PropServerRequestValidateEnabled = "server.validate.request.enabled" PropServerPprofEnabled = "server.pprof.enabled" PropServerGenerateEndpointDocEnabled = "server.generate-endpoint-doc.enabled" PropServerRequestAutoMapHeader = "server.request.mapping.header" PropServerGinValidationDisabled = "server.gin.validation.disabled" PropSqliteFile = "sqlite.file" PropSqliteWalEnabled = "sqlite.wal.enabled" PropRabbitMqEnabled = "rabbitmq.enabled" PropRabbitMqHost = "rabbitmq.host" PropRabbitMqPort = "rabbitmq.port" PropRabbitMqUsername = "rabbitmq.username" PropRabbitMqPassword = "rabbitmq.password" PropRabbitMqVhost = "rabbitmq.vhost" PropRabbitMqConsumerQos = "rabbitmq.consumer.qos" PropTracingPropagationKeys = "tracing.propagation.keys" PropLoggingLevel = "logging.level" PropLoggingRollingFile = "logging.rolling.file" PropLoggingRollingFileMaxAge = "logging.file.max-age" PropLoggingRollingFileMaxSize = "logging.file.max-size" PropLoggingRollingFileMaxBackups = "logging.file.max-backups" PropLoggingRollingFileRotateDaily = "logging.file.rotate-daily" PropTaskSchedulingEnabled = "task.scheduling.enabled" PropTaskSchedulingGroup = "task.scheduling.group" PropJwtPublicKey = "jwt.key.public" PropJwtPrivateKey = "jwt.key.private" PropJwtIssue = "jwt.key.issuer" PropMetricsEnabled = "metrics.enabled" PropMetricsRoute = "metrics.route" PropMetricsAuthEnabled = "metrics.auth.enabled" PropMetricsAuthBearer = "metrics.auth.bearer" PropMetricsEnableMemStatsLogJob = "metrics.memstat.log.job.enabled" PropMetricsMemStatsLogJobCron = "metrics.memstat.log.job.cron" PropConfigExtraFiles = "config.extra.files" )
const ( // Components like database that are essential and must be ready before anything else. BootstrapOrderL1 = -20 // Components that are bootstraped before the web server, such as metrics stuff. BootstrapOrderL2 = -15 // The web server or anything similar, bootstraping web server doesn't really mean that we will receive inbound requests. BootstrapOrderL3 = -10 // Components that introduce inbound requests or job scheduling. // // When these components bootstrap, the server is considered truly running. // For example, service registration (for service discovery), MQ broker connection and so on. BootstrapOrderL4 = -5 ExtraDesc = "miso-Desc" ExtraScope = "miso-Scope" ExtraResource = "miso-Resource" ExtraQueryParam = "miso-QueryParam" ExtraHeaderParam = "miso-HeaderParam" ExtraJsonRequest = "miso-JsonRequest" ExtraJsonResponse = "miso-JsonResponse" ScopePublic = "PUBLIC" ScopeProtected = "PROTECTED" TagQueryParam = "form" TagHeaderParam = "header" )
const ( XTraceId = "X-B3-TraceId" XSpanId = "X-B3-SpanId" )
const ( TagValidationV1 = "validation" // name of validation tag TagValidationV2 = "valid" // name of validation tag (v2) ValidMaxLen = "maxLen" // max length of a string, array, slice, e.g., `valid:"maxLen:10"` ValidNotEmpty = "notEmpty" // not empty, supports string, array, slice, map ValidNotNil = "notNil" // not nil, only validates slice, map, pointer, func // must be one of the values listed, e.g., 'valid:"member:PUBLIC|PROTECTED"', means that the tag value must be either PUBLIC or PROTECTED. // only string type is supported. ValidMember = "member" ValidPositive = "positive" // greater than 0, only supports int... or string type ValidPositiveOrZero = "positiveOrZero" // greater than or equal to 0, only supports int... or string type ValidNegative = "negative" // less than 0, only supports int... or string type ValidNegativeOrZero = "negativeOrZero" // less than or equal to 0, only supports int... or string type ValidNotZero = "notZero" // not zero, only supports int... or string type Validated = "validated" // mark a nested struct or pointer validated, nil pointer is ignored, one may combine "notNil,validated" )
const ( BoolStrTrue = "true" BoolStrFalse = "false" )
const (
Bearer = "Bearer"
)
const (
DEFAULT_LEN = 35
)
const (
DEFAULT_QOS = 68 // default QOS
)
const (
// Default File Mode
DefFileMode = 0666
)
const (
DefaultPageLimit = 30
)
const (
ErrCodeGeneric = "XXXX"
)
const (
TagApiDocDesc = "desc"
)
const (
Version = "v0.0.30"
)
Variables ¶
var ( // Select Server randomly. RandomServerSelector ServerSelector = func(servers []Server) int { return rand.Int() % len(servers) } // Property based ServiceRegistry PropBasedServiceRegistry = HardcodedServiceRegistry{} // ServerList based ServiceRegistry // // Server selection can be customized by replacing the Rule. DynamicServiceRegistry = ServerListServiceRegistry{Rule: RandomServerSelector} ErrMissingServiceName = errors.New("service name is required") ErrServiceInstanceNotFound = errors.New("unable to find any available service instance") ErrServerListNotFound = errors.New("fail to find ServerList implemnetation") // Get ServerList implementation GetServerList func() ServerList )
var ( ErrMissingPrivateKey = errors.New("missing private key") ErrMissingPublicKey = errors.New("missing public key") ErrExtractClaimFailed = errors.New("unable to extract claims from token") )
var ( PUB_PEM_BEGIN = "-----BEGIN PUBLIC KEY-----" PUB_PEM_END = "-----END PUBLIC KEY-----" PRIV_PEM_BEGIN = "-----BEGIN PRIVATE KEY-----" PRIV_PEM_END = "-----END PRIVATE KEY-----" ErrDecodePemFailed = errors.New("failed to decode public key pem") ErrInvalidKey = errors.New("invalid key") )
var ( ValidateWalkTagCallbackDeprecated = WalkTagCallback{ Tag: TagValidationV1, OnWalked: validateOnWalked, } ValidateWalkTagCallback = WalkTagCallback{ Tag: TagValidationV2, OnWalked: validateOnWalked, } )
var (
ApiDocTypeAlias = map[string]string{
"ETime": "int64",
"*ETime": "int64",
"*miso.ETime": "int64",
}
)
var ( // Api for Consul. ConsulApi = ConsulApiImpl{} )
var (
ErrGetTimeout = errors.New("future.TimedGet timeout")
)
var (
MetricsMemoryMatcher = regexp.MustCompile(`^/memory/.*`)
)
var (
MisoDefaultClient *http.Client
)
Functions ¶
func AddHealthIndicator ¶ added in v0.0.6
func AddHealthIndicator(hi HealthIndicator)
Add health indicator.
func AddMySQLBootstrapCallback ¶ added in v0.0.28
func AddMySQLBootstrapCallback(cbk MySQLBootstrapCallback)
func AddPropagationKeys ¶ added in v0.0.27
func AddPropagationKeys(keys ...string)
Add propagation key for tracing
func AddRabbitListener ¶
func AddRabbitListener(listener RabbitListener)
Register pending message listener.
Listeners will be started in StartRabbitMqClient func when the connection to broker is established.
For any message that the listener is unable to process (returning error), the message is redelivered indefinitively with a delay of 10 seconds until the message is finally processed without error.
func AddShutdownHook ¶
func AddShutdownHook(hook func())
Register shutdown hook, hook should never panic
func AppendableFile ¶ added in v0.0.14
Create appendable file with 0666 permission.
func BearerAuth ¶ added in v0.0.20
func BearerAuth(delegate http.Handler, getExpectedToken func() string) http.HandlerFunc
func BootstrapServer ¶
func BootstrapServer(args []string)
Bootstrap server
This func will attempt to create http server, connect to MySQL, Redis or Consul based on the configuration loaded.
It also handles service registration/de-registration on Consul before Gin bootstraped and after SIGTERM/INTERRUPT signals are received.
Graceful shutdown for the http server is also enabled and can be configured through props.
To configure server, MySQL, Redis, Consul and so on, see PROPS_* in prop.go.
It's also possible to register callbacks that are triggered before/after server bootstrap
server.PreServerBootstrap(func(c Rail) error { // do something right after configuration being loaded, but server hasn't been bootstraped yet }); server.PostServerBootstrapped(func(c Rail) error { // do something after the server bootstrap }); // start the server server.BootstrapServer(os.Args)
func BuildRollingLogFileWriter ¶
func BuildRollingLogFileWriter(p NewRollingLogFileParam) *lumberjack.Logger
Create rolling file based logger
func ChainValidationError ¶
func ClientSkipTlsSecureCheck ¶ added in v0.0.4
func ClientSkipTlsSecureCheck()
Disable TLS certificate check.
func CollectTypeFields ¶
func CollectTypeFields(eleType reflect.Type) []reflect.StructField
Get Fields of A Type
func ConfigureLogging ¶
Configure logging level and output target based on loaded configuration.
func ConsulBootstrap ¶
func ConsulBootstrapCondition ¶ added in v0.0.8
func CopyFilter ¶ added in v0.0.29
Filter slice value, the original slice is copied before filtering.
func DebugTimeOp ¶
Run timer for named operation and print result in log
e.g.,
defer DebugTimeOp(ec, time.Now(), "someOperation")
func DeclareRabbitBinding ¶
func DeclareRabbitBinding(ch *amqp.Channel, bind BindingRegistration) error
Declare binding using the provided channel immediately
func DeclareRabbitExchange ¶
func DeclareRabbitExchange(ch *amqp.Channel, exchange ExchangeRegistration) error
Declare exchange using the provided channel immediately
func DeclareRabbitQueue ¶
func DeclareRabbitQueue(ch *amqp.Channel, queue QueueRegistration) error
Declare queue using the provided channel immediately
func DecodeJson ¶ added in v0.0.6
Decode JSON using jsoniter.
func DefaultHealthCheck ¶
Create a default health check endpoint that simply doesn't nothing except returing 200
func DefaultMetricDesc ¶ added in v0.0.13
func DefaultMetricDesc(matcher *regexp.Regexp) []metrics.Description
func DefaultReadConfig ¶
Default way to read config file.
Repetitively calling this method overides previously loaded config.
You can also use ReadConfig to load your custom configFile. This func is essentially:
LoadConfigFromFile(GuessConfigFilePath(args))
Notice that the loaded configuration can be overriden by the cli arguments as well by using `KEY=VALUE` syntax.
func DeregisterConsulService ¶ added in v0.0.28
func DeregisterConsulService() error
Deregister current service
func DispatchErrMsgJson ¶
Dispatch error response in json format
func DispatchJsonCode ¶ added in v0.0.18
Dispatch a json response
func DistriTaskBootstrap ¶ added in v0.0.12
func EnableBasicAuth ¶ added in v0.0.30
Enable Basic authorization globally for all registered endpoints.
func EncodeJson ¶ added in v0.0.6
Encode JSON using jsoniter.
func ExtractArgValue ¶
Parse CLI Arg to extract a value from arg, [key]=[value]
e.g.,
To look for 'configFile=?'.
path := ExtractArgValue(args, func(key string) bool { return key == "configFile" }).
func FastDistinct ¶ added in v0.0.28
Filter duplicate values, faster but values are sorted, and the slice values are filtered in place.
func Filter ¶ added in v0.0.28
Filter slice values in place. Be cautious that both slices are backed by the same array.
func FilterMetricDesc ¶ added in v0.0.13
func FuzzParseTime ¶ added in v0.0.18
func GenId ¶
func GenId() (id string)
Generate Id
The id consists of [64 bits long] + [6 digits machine_code] The 64 bits long consists of: [sign bit (1 bit)] + [timestamp (49 bits, ~1487.583 years)] + [sequenceNo (14 bits, 0~16383)]
The max value of Long is 9223372036854775807, which is a string with 19 characters, so the generated id will be of at most 25 characters ¶
This func is thread-safe
func GenIdP ¶
Generate Id with prefix
The id consists of [64 bits long] + [6 digits machine_code] The 64 bits long consists of: [sign bit (1 bit)] + [timestamp (49 bits, ~1487.583 years)] + [sequenceNo (14 bits, 0~16383)]
The max value of Long is 9223372036854775807, which is a string with 19 characters, so the generated id will be of at most 25 characters ¶
This func is thread-safe
func GetConsulClient ¶
Get the already created consul client.
InitConsulClient() must be called before this func.
If the client is not already created, this func will panic.
func GetCtxStr ¶
Get value from context as a string
int*, unit*, float* types are formatted as string, other types are returned as empty string
func GetEnvElse ¶
Get environment variable with default value
func GetPropDur ¶ added in v0.0.14
Get prop as time.Duration
func GetPropStr ¶
Get prop as string
If the value is an argument that can be expanded, the actual value will be resolved if possible.
e.g, for "name" : "${secretName}".
This func will attempt to resolve the actual value for '${secretName}'.
func GetPropStrMap ¶ added in v0.0.14
Get prop as string based map.
func GetPropStrSlice ¶ added in v0.0.3
Get prop as string slice
func GetSqlite ¶
Get sqlite client.
Client is initialized if necessary.
This func looks for prop:
PROP_SQLITE_FILE
func GuessConfigFilePath ¶
Guess config file path.
It first looks for the arg that matches the pattern "configFile=/path/to/configFile". If none is found, it's by default 'conf.yml'.
func HandleEndpointResult ¶ added in v0.0.23
Handle endpoint's result using the configured EndpointResultHandler.
func HasPrefixIgnoreCase ¶ added in v0.0.5
Check if s has the prefix in a case-insensitive way.
func HasScheduledJobs ¶ added in v0.0.9
func HasScheduledJobs() bool
Whether scheduler is initialized
func HasSuffixIgnoreCase ¶ added in v0.0.6
Check if s has the suffix in a case-insensitive way.
func InitConsulClient ¶ added in v0.0.14
func InitConsulClient() error
Get or init new consul client
For the first time that the consul client is initialized, this func will look for prop:
"consul.consulAddress"
func InitMySQL ¶
func InitMySQL(rail Rail, p MySQLConnParam) error
Init Handle to the database
If mysql client has been initialized, current func call will be ignored.
func InitMySQLFromProp ¶
Init connection to mysql
If mysql client has been initialized, current func call will be ignored.
This func looks for following props:
"mysql.user" "mysql.password" "mysql.database" "mysql.host" "mysql.port" "mysql.connection.parameters"
func InitRedis ¶
func InitRedis(rail Rail, p RedisConnParam) (*redis.Client, error)
Initialize redis client
If redis client has been initialized, current func call will be ignored
func InitRedisFromProp ¶
Initialize redis client from configuration
If redis client has been initialized, current func call will be ignored.
This func looks for following prop:
"redis.address" "redis.port" "redis.username" "redis.password" "redis.database"
func IsConsulClientInitialized ¶
func IsConsulClientInitialized() bool
Check whether consul client is initialized
func IsConsulServiceRegistered ¶ added in v0.0.13
func IsConsulServiceRegistered() bool
Check if current instance is registered on consul.
func IsLocalAddress ¶
Check whether the address is local (localhost/127.0.0.1)
func IsMySqlEnabled ¶
func IsMySqlEnabled() bool
Check if mysql is enabled
This func looks for following prop:
"mysql.enabled"
func IsRLockNotObtainedErr ¶
Check whether the error is 'redislock.ErrNotObtained'
func IsRedisClientInitialized ¶
func IsRedisClientInitialized() bool
Check whether redis client is initialized
func IsRedisEnabled ¶
func IsRedisEnabled() bool
Check if redis is enabled
This func looks for following prop:
"redis.enabled"
func IsTaskSchedulingDisabled ¶
func IsTaskSchedulingDisabled() bool
Check if it's disabled (based on configuration, doesn't affect method call)
func JoinQueryParam ¶
Join query parameters
func LTimeOp ¶
Run timer for named operation and print result
e.g.,
defer LTimeOp(ec, time.Now(), "someOperation")
func LoadConfigFromFile ¶
Load config from file
Repetitively calling this method overides previously loaded config.
func LoadConfigFromReader ¶ added in v0.0.29
Load config from reader.
It's the caller's responsibility to close the provided reader.
Repetitively calling this method overides previously loaded config.
func LoadPrivKey ¶
func LoadPrivKey(content string) (*rsa.PrivateKey, error)
func LoadPropagationKeys ¶ added in v0.0.7
func LoadPropagationKeys(r Rail)
Read property and find propagation keys .
This func looks for following property.
"tracing.propagation.keys"
func LowercaseNamingStrategy ¶ added in v0.0.3
Change first rune to lower case.
func ManualBootstrapPrometheus ¶ added in v0.0.13
func ManualBootstrapPrometheus()
Caller wants to bootstrap prometheus manually.
This is mainly used for gateway that implements handler for all endpoints.
func ManualPprofRegister ¶ added in v0.0.15
func ManualPprofRegister()
Registrer pprof debug endpoint manually.
func MkdirParentAll ¶ added in v0.0.30
MkdirAll but only for the parent directory of the path, perm 0755 is used.
The path should always point to a specific file under some directories, as this method always attempts to extract parent dir of the file. It the path fails to fulfill this requirement, the output might be unexpected.
func MySQLBootstrap ¶
func MySQLBootstrapCondition ¶ added in v0.0.8
func NewDeleteRequest ¶
Create DELETE request
func NewEventBus ¶
func NewEventBus(name string)
Declare event bus.
It basically is to create an direct exchange and a queue identified by the name, and bind them using routing key '#'.
func NewMySQLConn ¶
func NewMySQLConn(rail Rail, p MySQLConnParam) (*gorm.DB, error)
Create new MySQL connection
func NewOptionsRequest ¶
Create OPTIONS request
func NewPostRequest ¶
Create POST request
func NewPromCounter ¶ added in v0.0.6
func NewPromCounter(name string) prometheus.Counter
Create new Counter.
The Counter with this name is automatically registered to the prometheus.DefaultRegisterer.
func NewPromHisto ¶ added in v0.0.13
func NewPromHisto(name string) prometheus.Histogram
Create new Histogram.
The created Histogram is automatically registered to the prometheus.DefaultRegisterer.
func NewPromHistoVec ¶ added in v0.0.13
func NewPromHistoVec(name string, labels []string) *prometheus.HistogramVec
Create new HistogramVec.
The HistogramVec is automatically registered to the prometheus.DefaultRegisterer.
func NewPutRequest ¶
Create PUT request
func NewRabbitChan ¶
Create new channel from the established connection
func NewSubmitAsyncFunc ¶ added in v0.0.30
Create func that calls SubmitAsync(...) with the given pool.
func PTimeOp ¶
Run timer for named operation and print result in log
e.g.,
defer PTimeOp(time.Now(), "someOperation")
func ParseBearer ¶ added in v0.0.13
func PerfLogExclPath ¶
func PerfLogExclPath(path string)
Ask PerfMiddleware to stop measuring perf of provided path
func PerfMiddleware ¶
func PerfMiddleware() gin.HandlerFunc
Perf Middleware that calculates how much time each request takes
func PostJobExec ¶ added in v0.0.8
func PostJobExec(hook PostJobHook)
Callback triggered after job execution.
Other callbacks will still be executed even if one of them returns error.
Callback will be ignored, if the scheduler is already running.
func PostServerBootstrapped ¶
Add listener that is invoked when server is finally bootstrapped
This usually means all server components are started, such as MySQL connection, Redis Connection and so on.
Caller is free to call PostServerBootstrapped inside another PostServerBootstrapped callback.
func PreConfiguredFormatter ¶
Get pre-configured TextFormatter for logrus
func PreJobExec ¶ added in v0.0.8
func PreJobExec(hook PreJobHook)
Callback triggered before job execution.
The job and other callbacks will still be executed even if one of the callback returns error.
Callback will be ignored, if the scheduler is already running.
func PreProcessGin ¶ added in v0.0.16
func PreProcessGin(preProcessor GinPreProcessor)
Process *gin.Engine before the web server starts, particularly useful when trying to add middleware.
func PreServerBootstrap ¶
Add listener that is invoked before the server is fully bootstrapped
This usually means that the configuration is loaded, and the logging is configured, but the server components are not yet initialized.
Caller is free to call PostServerBootstrapped or PreServerBootstrap inside another PreServerBootstrap callback.
func PrepareWebStaticFs ¶ added in v0.0.29
Prepare to serve static files in embedded fs.
Static files are all served by paths with prefix '/static'.
Notice that index.html must be renamed to index.htm or else it won't work.
If you are using Angular framework, you may add extra build param as follows. The idea is still the same for other frameworks.
ng build --baseHref=/static/
func PrometheusBootstrap ¶
func PrometheusBootstrapCondition ¶ added in v0.0.8
func PrometheusHandler ¶
Default handler for prometheus metrics.
func PubEventBus ¶
Send msg to event bus.
It's identical to sending a message to an exchange identified by the name using routing key '#'.
Before calling this method, the NewEventBus(...) should be called at least once to create the necessary components.
func PublishJson ¶
Publish json message with confirmation
func PublishMsg ¶
func PublishMsg(c Rail, msg []byte, exchange string, routingKey string, contentType string, headers map[string]any) error
Publish message with confirmation
func PublishText ¶
Publish plain text message with confirmation
func RLockExec ¶
Lock and run the runnable using Redis
The maximum time wait for the lock is 1s, retry every 5ms.
May return 'redislock.ErrNotObtained' when it fails to obtain the lock.
func RLockRun ¶
Lock and run the runnable using Redis
The maximum time wait for the lock is 1s, retry every 5ms.
May return 'redislock:ErrNotObtained' when it fails to obtain the lock.
func RabbitBootstrap ¶
func RabbitBootstrapCondition ¶ added in v0.0.8
func RandAlpha ¶
Generate random alphabetic string with specified length
the generated string will contains [a-zA-Z]
func RandLowerAlpha ¶
Generate random alphabetic, lowercase string with specified length
the generated string will contains [a-z]
func RandLowerAlphaNumeric ¶
Generate random alphabetic, lowercase string with specified length
the generated string will contains [a-z0-9]
func RandLowerAlphaNumeric16 ¶ added in v0.0.25
func RandLowerAlphaNumeric16() string
Same as RandLowerAlphaNumeric(16) but with less allocation.
func RandNum ¶
Generate random numeric string with specified length
the generated string will contains [0-9]
func RandStr ¶
Generate random string with specified length
the generated string will contains [a-zA-Z0-9]
ERand() is preferred for higher entrophy
func RandUpperAlpha ¶
Generate random alphabetic, uppercase string with specified length
the generated string will contains [A-Z]
func RandUpperAlphaNumeric ¶
Generate random alphabetic, uppercase string with specified length
the generated string will contains [A-Z0-9]
func RawAny ¶
func RawAny(url string, handler RawTRouteHandler, extra ...StrPair)
Register ANY request route (raw version)
func ReadFileAll ¶ added in v0.0.22
Read all content from file.
func ReadWriteFile ¶ added in v0.0.15
Create readable & writable file with 0666 permission.
func RedisBootstrap ¶
func RedisBootstrapCondition ¶ added in v0.0.8
func RegisterBootstrapCallback ¶
func RegisterBootstrapCallback(bootstrapComponent ComponentBootstrap)
Register server component bootstrap callback
When such callback is invoked, configuration should be fully loaded, the callback is free to read the loaded configuration and decide whether or not the server component should be initialized, e.g., by checking if the enable flag is true.
func RegisterConsulService ¶ added in v0.0.28
func RegisterConsulService() error
Register current instance as a service
If we have already registered before, current method call will be ignored.
This func looks for following prop:
"server.port" "consul.registerName" "consul.healthCheckInterval" "consul.registerAddress" "consul.healthCheckUrl" "consul.healthCheckTimeout" "consul.healthCheckFailedDeregisterAfter"
func RegisterRabbitBinding ¶
func RegisterRabbitBinding(b BindingRegistration)
Declare binding on client initialization
func RegisterRabbitExchange ¶
func RegisterRabbitExchange(e ExchangeRegistration)
Declare exchange on client initialization
func RegisterRabbitQueue ¶
func RegisterRabbitQueue(q QueueRegistration)
Declare queue on client initialization
func ResolveArg ¶
Resolve argument, e.g., for arg like '${someArg}', it will in fact look for 'someArg' in os.Env
func ResolveServerHost ¶
Resolve server host, use IPV4 if the given address is empty or '0.0.0.0'
func SWriteJson ¶ added in v0.0.29
Write JSON as string using jsoniter.
func ScheduleCron ¶
add a cron job to scheduler, note that the cron expression includes second, e.g., '*/1 * * * * *'
this func doesn't start the scheduler
func ScheduleDistributedTask ¶
Schedule a named distributed task
Applications are grouped together as a cluster (each cluster is differentiated by its group name), only the master node can run the Scheduled tasks.
Tasks are pending until StartTaskSchedulerAsync() is called.
E.g.,
job := miso.Job{ Name: "Very important task", Cron: "0/1 * * * * ?", CronWithSeconds: true, Run: MyTask, } ScheduleDistributedTask(job)
func SchedulerBootstrap ¶
func ServeTempl ¶ added in v0.0.29
func SetDefaultTimeout ¶ added in v0.0.6
Set default http client timeout
func SetLogLevel ¶ added in v0.0.8
func SetLogLevel(level string)
func SetMachineCode ¶
Overwrite the randomly generated machine code, machine code must be between 0 and 999999, at most 6 digits.
func SetResultBodyBuilder ¶ added in v0.0.25
func SetResultBodyBuilder(rbb ResultBodyBuilder) error
Replace the default ResultBodyBuilder
func SetScheduleGroup ¶
func SetScheduleGroup(groupName string)
Set the schedule group for current node, by default it's 'default'
func ShuffleRunes ¶
func ShuffleStr ¶
func SprintMemStats ¶ added in v0.0.13
func SqliteBootstrap ¶ added in v0.0.8
func SqliteBootstrapCondition ¶ added in v0.0.8
func StartRabbitMqClient ¶
Start RabbitMQ Client (synchronous for the first time, then auto-reconnect later in another goroutine)
This func will attempt to establish connection to broker, declare queues, exchanges and bindings.
Listeners are also created once the intial setup is done.
When connection is lost, it will attmpt to reconnect to recover, unless the given context is done.
To register listener, please use 'AddListener' func.
func StartSchedulerBlocking ¶
func StartSchedulerBlocking()
Start scheduler and block current routine
func StartTaskSchedulerAsync ¶
Start distributed scheduler asynchronously
func StartTaskSchedulerBlocking ¶
Start distributed scheduler, current routine is blocked
func SubEventBus ¶
Subscribe to event bus.
Internally, it calls NewEventBus(...) and registers a listener for the queue identified by the bus name.
func SubscribeServerChanges ¶ added in v0.0.19
Subscribe to changes to service instances.
Callback is triggered asynchronously.
func TermOpenUrl ¶ added in v0.0.29
func TimeOp ¶
Run timer for named operation and print result in log
e.g.,
defer TimeOp(ec, time.Now(), "someOperation")
func TraceLogger ¶
Return logger with tracing infomation
func TraceRequest ¶
Wraper request with tracing key/value pairs on http headers
func UnmarshalFromPropKey ¶ added in v0.0.22
Unmarshal configuration from a speicific key.
func UnsafeByt2Str ¶ added in v0.0.26
Convert []byte to string without alloc.
Both the []byte and the string share the same memory.
Any modification on the original []byte is reflected on the returned string.
byt = []byte("abc") s = UnsafeByt2Str(byt) // "abc" using the same memory byt[0] = 'd' // modified in place at 0, also reflected on s ("dbc")
Tricks from https://github.com/valyala/fasthttp.
func UnsafeStr2Byt ¶ added in v0.0.26
Convert string to []byte without alloc.
Both the []byte and the string share the same memory.
The resulting []byte is not modifiable, program will panic if modified.
s := "abc" byt := UnsafeStr2Byt(s) // "abc" but in []byte byt[0] = 'd' // will panic
Tricks from https://github.com/valyala/fasthttp.
func UsePropagationKeys ¶ added in v0.0.25
func UsePropagationKeys(forEach func(key string))
func Validate ¶
Validate target object based on the validation rules specified by tags 'valid:"[RULE]"'.
Available Rules:
- maxLen
- notEmpty
- notNil
- positive
- positiveOrZero
- negative
- negativeOrZero
- notZero
- validated
func ValidateIntRule ¶
func ValidateIssuer ¶
func ValidateIssuer() jwt.ParserOption
func ValidateRule ¶
func WalkTagShallow ¶ added in v0.0.26
func WalkTagShallow(ptr any, callbacks ...WalkTagCallback) error
Walk fields of *struct, won't go deeper even if the field is a struct.
func WebServerBootstrap ¶
func WebServerBootstrapCondition ¶ added in v0.0.8
Types ¶
type AsyncPool ¶ added in v0.0.14
type AsyncPool struct {
// contains filtered or unexported fields
}
A long live, bounded pool of goroutines.
Use miso.NewAsyncPool to create a new pool.
AsyncPool internally maintains a task queue with limited size and limited number of workers. If the task queue is full, the caller of *AsyncPool.Go is blocked indefinitively.
func NewAsyncPool ¶ added in v0.0.14
Create a bounded pool of goroutines.
The maxTasks determines the capacity of the task queues. If the task queue is full, the caller of *AsyncPool.Go is blocked.
The maxWorkers determines the max number of workers.
type AwaitFutures ¶ added in v0.0.18
type AwaitFutures[T any] struct { // contains filtered or unexported fields }
AwaitFutures represent multiple tasks that will be submitted to the pool asynchronously whose results will be awaited together.
AwaitFutures should only be used once everytime it's needed.
Use miso.NewAwaitFutures() to create one.
func NewAwaitFutures ¶ added in v0.0.18
func NewAwaitFutures[T any](pool *AsyncPool) *AwaitFutures[T]
func (*AwaitFutures[T]) Await ¶ added in v0.0.18
func (a *AwaitFutures[T]) Await() []Future[T]
func (*AwaitFutures[T]) SubmitAsync ¶ added in v0.0.18
func (a *AwaitFutures[T]) SubmitAsync(task func() (T, error))
type BindingRegistration ¶
type CTFormatter ¶
type CTFormatter struct { }
type ComponentBootstrap ¶
type ComponentBootstrap struct { // name of the component. Name string // the actual bootstrap function. Bootstrap func(rail Rail) error // check whether component should be bootstraped Condition func(rail Rail) (bool, error) // order of which the components are bootstraped, natural order, it's by default 15. Order int }
type ConsulApiImpl ¶ added in v0.0.6
type ConsulApiImpl struct{}
func (ConsulApiImpl) CatalogFetchServiceNames ¶ added in v0.0.6
func (c ConsulApiImpl) CatalogFetchServiceNames(rail Rail) (map[string][]string, error)
Fetch all registered services, this method always call Consul instead of reading from cache
func (ConsulApiImpl) CatalogFetchServiceNodes ¶ added in v0.0.6
func (c ConsulApiImpl) CatalogFetchServiceNodes(rail Rail, name string) ([]*api.CatalogService, error)
Fetch registered service by name, this method always call Consul instead of reading from cache
func (ConsulApiImpl) DeregisterService ¶ added in v0.0.6
func (c ConsulApiImpl) DeregisterService(serviceId string) error
func (ConsulApiImpl) RegisterService ¶ added in v0.0.12
func (c ConsulApiImpl) RegisterService(registration *api.AgentServiceRegistration) error
type ConsulServerList ¶ added in v0.0.28
Holder of a list of ServiceHolder
func (*ConsulServerList) IsSubscribed ¶ added in v0.0.28
func (s *ConsulServerList) IsSubscribed(rail Rail, service string) bool
func (*ConsulServerList) ListServers ¶ added in v0.0.28
func (s *ConsulServerList) ListServers(rail Rail, name string) []Server
func (*ConsulServerList) PollInstance ¶ added in v0.0.28
func (s *ConsulServerList) PollInstance(rail Rail, name string) error
Fetch and cache services nodes.
func (*ConsulServerList) PollInstances ¶ added in v0.0.28
func (s *ConsulServerList) PollInstances(rail Rail) error
func (*ConsulServerList) Subscribe ¶ added in v0.0.28
func (s *ConsulServerList) Subscribe(rail Rail, service string) error
func (*ConsulServerList) Unsubscribe ¶ added in v0.0.28
func (s *ConsulServerList) Unsubscribe(rail Rail, service string) error
func (*ConsulServerList) UnsubscribeAll ¶ added in v0.0.28
func (s *ConsulServerList) UnsubscribeAll(rail Rail) error
type ETime ¶
EpochTime, same as time.Time but will be serialized/deserialized as epoch milliseconds
This type can be safely used in GORM just like time.Time
func (ETime) FormatClassic ¶
func (ETime) FormatClassicLocale ¶ added in v0.0.9
func (ETime) MarshalJSON ¶
func (*ETime) UnmarshalJSON ¶
implements decorder.Unmarshaler in encoding/json.
type EventPipeline ¶ added in v0.0.26
type EventPipeline[T any] struct { // contains filtered or unexported fields }
EventPipeline is a thin wrapper of NewEventBus, SubEventBus and PubEventBus. It's used to make things easier and more consistent.
Use NewEventPipeline to instantiate.
func NewEventPipeline ¶ added in v0.0.26
func NewEventPipeline[T any](name string) EventPipeline[T]
Create new EventPipeline. NewEventBus is internally called as well.
func (*EventPipeline[T]) Listen ¶ added in v0.0.26
func (ep *EventPipeline[T]) Listen(concurrency int, listener func(rail Rail, t T) error)
Call SubEventBus.
func (*EventPipeline[T]) Name ¶ added in v0.0.27
func (ep *EventPipeline[T]) Name() string
func (*EventPipeline[T]) Send ¶ added in v0.0.26
func (ep *EventPipeline[T]) Send(rail Rail, event T) error
Call PubEventBus.
type ExchangeRegistration ¶
type ForEachField ¶
type ForEachField func(index int, field reflect.StructField) (breakIteration bool)
type Future ¶
type GinPreProcessor ¶ added in v0.0.16
Preprocessor of *gin.Engine.
type GnResp ¶
type GnResp[T any] struct { ErrorCode string `json:"errorCode" desc:"error code"` Msg string `json:"msg" desc:"message"` Error bool `json:"error" desc:"whether the request was successful"` Data T `json:"data" desc:"response data"` }
Generic version of Resp
type HardcodedServiceRegistry ¶ added in v0.0.14
type HardcodedServiceRegistry struct { }
Service registry backed by loaded configuration.
func (HardcodedServiceRegistry) ListServers ¶ added in v0.0.14
func (r HardcodedServiceRegistry) ListServers(rail Rail, service string) ([]Server, error)
func (HardcodedServiceRegistry) ResolveUrl ¶ added in v0.0.14
type HealthIndicator ¶ added in v0.0.6
type HealthIndicator struct { Name string // name of the indicator CheckHealth func(rail Rail) bool // Check health }
Indicator of health status
type HealthStatus ¶ added in v0.0.6
type HistTimer ¶ added in v0.0.13
type HistTimer struct {
// contains filtered or unexported fields
}
Timer based on prometheus.Histogram.
Duration is measured in millisecond.
Use NewHistTimer to create a new one, and each timer can only be used for once.
func NewHistTimer ¶ added in v0.0.13
func NewHistTimer(hist prometheus.Histogram) *HistTimer
Create new timer that is backed by a prometheus.Histogram. Each timer can only be used for once.
func (*HistTimer) ObserveDuration ¶ added in v0.0.13
type HttpRoute ¶
type HttpRoute struct { Url string Method string Extra map[string][]any Desc string // description of the route (metadata). Scope string // the documented access scope of the route, it maybe "PUBLIC" or something else (metadata). Resource string // the documented resource that the route should be bound to (metadata). Headers []ParamDoc // the documented header parameters that will be used by the endpoint (metadata). QueryParams []ParamDoc // the documented query parameters that will used by the endpoint (metadata). JsonRequestVal any // the documented json request value that is expected by the endpoint (metadata). JsonResponseVal any // the documented json response value that will be returned by the endpoint (metadata). }
type HttpRouteDoc ¶ added in v0.0.23
type HttpRouteDoc struct { Url string Method string Extra map[string][]any Desc string // description of the route (metadata). Scope string // the documented access scope of the route, it maybe "PUBLIC" or something else (metadata). Resource string // the documented resource that the route should be bound to (metadata). Headers []ParamDoc // the documented header parameters that will be used by the endpoint (metadata). QueryParams []ParamDoc // the documented query parameters that will used by the endpoint (metadata). JsonRequestDesc []jsonDesc // the documented json request type that is expected by the endpoint (metadata). JsonResponseDesc []jsonDesc // the documented json response type that will be returned by the endpoint (metadata). Curl string }
type Inbound ¶ added in v0.0.26
type Inbound struct {
// contains filtered or unexported fields
}
Inbound request context.
Inbound hides the underlying engine (e.g., *gin.Context) using .Engine() method. In most cases, you should not attempt to cast the engine explictly, it's possible that miso will replace the engine in future release.
However, you should be able to satisfy most of your need by calling .Unwrap(), that returns the underlying http.ResponseWriter, *http.Request.
Use miso.Rail for tracing (not just logs), pass it around your application code and the code calling miso's methods course.
func (*Inbound) HandleResult ¶ added in v0.0.26
Handle the result using universally configured handler.
The result or error is written back to the client. In most cases, caller must exit the handler after calling this method. Theoritically, this method is only useful for RawGet, RawPut, RawPost, RawDelete. Other methods, such as IGet, IPost, Post, Put or Delete, handle the results automatically in exactly the same way.
E.g.,
miso.RawGet("/dir/info", func(inb *miso.Inbound) { // ... do something if err != nil { inb.HandleResult(nil, err) // something goes wrong return } // return result back to the client inb.HandleResult(result, err) })
type Introspector ¶
type Introspector struct { Type reflect.Type Fields []reflect.StructField // contains filtered or unexported fields }
func (*Introspector) Field ¶
func (it *Introspector) Field(fieldName string) (field reflect.StructField, isFieldFound bool)
Get field by name
func (*Introspector) FieldAt ¶
func (it *Introspector) FieldAt(idx int) (field reflect.StructField)
Get field at index
func (*Introspector) FieldIdx ¶
func (it *Introspector) FieldIdx(fieldName string) (index int, isFieldFound bool)
Get field index
func (*Introspector) IterFields ¶
func (it *Introspector) IterFields(forEach ForEachField)
Iterate fields
func (*Introspector) Tag ¶
func (it *Introspector) Tag(fieldName string, tagName string) (tag string, isFieldFound bool)
Get tag by of field
func (*Introspector) TagRetriever ¶
func (it *Introspector) TagRetriever(fieldName string) (t TagRetriever, isFieldFound bool)
Get tag retriever for a field
type Job ¶ added in v0.0.8
type Job struct { Name string // name of the job. Cron string // cron expr. CronWithSeconds bool // whether cron expr contains the second field. Run func(Rail) error // actual job execution logic. LogJobExec bool // whether job execution should be logged, error msg is always logged and is not affected by this option. TriggeredOnBoostrapped bool // whether job should be triggered when server is fully bootstrapped }
type JobExecStats ¶ added in v0.0.8
type JsonMsgListener ¶
type JsonMsgListener[T any] struct { QueueName string Handler func(rail Rail, payload T) error NumOfRoutines int }
Json Message Listener for Queue
func (JsonMsgListener[T]) Concurrency ¶
func (m JsonMsgListener[T]) Concurrency() int
func (JsonMsgListener[T]) Handle ¶
func (m JsonMsgListener[T]) Handle(rail Rail, payload string) error
func (JsonMsgListener[T]) Queue ¶
func (m JsonMsgListener[T]) Queue() string
func (JsonMsgListener[T]) String ¶
func (m JsonMsgListener[T]) String() string
type JsonSerializer ¶ added in v0.0.18
type JsonSerializer struct { }
func (JsonSerializer) Deserialize ¶ added in v0.0.18
func (j JsonSerializer) Deserialize(ptr any, v string) error
type LazyRouteDecl ¶ added in v0.0.23
type LazyRouteDecl struct { Url string Method string Handler func(c *gin.Context) RegisterFunc func(extra ...StrPair) Extras []StrPair }
Lazy route declaration
func Delete ¶
func Delete[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecl
Register DELETE request.
The result and error are automatically wrapped to miso.Resp (see miso.SetResultBodyBuilder func) and serialized to json.
func Get ¶
func Get[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecl
Register GET request.
The result and error are automatically wrapped to miso.Resp (see miso.SetResultBodyBuilder func) and serialized to json.
func IDelete ¶
func IDelete[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecl
Register DELETE request.
Req type should be a struct, where all fields are automatically mapped from the request using 'json' tag or 'form' tag (for form-data, query param) or 'header' tag (only supports string/*string).
Res type should be a struct. By default both Res value and error (if not nil) will be wrapped inside miso.Resp and serialized to json. Wrapping to miso.Resp is customizable using miso.SetResultBodyBuilder func.
With both Req and Res type declared, miso will automatically parse these two types using reflect and generate an API documentation describing the endpoint.
func IGet ¶
func IGet[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecl
Register GET request.
Req type should be a struct, where all fields are automatically mapped from the request using 'form' tag (for form-data, query param) or 'header' tag (only supports string/*string).
Res type should be a struct. By default both Res value and error (if not nil) will be wrapped inside miso.Resp and serialized to json. Wrapping to miso.Resp is customizable using miso.SetResultBodyBuilder func.
With both Req and Res type declared, miso will automatically parse these two types using reflect and generate an API documentation describing the endpoint.
func IPost ¶
func IPost[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecl
Register POST request.
Req type should be a struct, where all fields are automatically mapped from the request using 'json' tag or 'form' tag (for form-data, query param) or 'header' tag (only supports string/*string).
Res type should be a struct. By default both Res value and error (if not nil) will be wrapped inside miso.Resp and serialized to json. Wrapping to miso.Resp is customizable using miso.SetResultBodyBuilder func.
With both Req and Res type declared, miso will automatically parse these two types using reflect and generate an API documentation describing the endpoint.
func IPut ¶
func IPut[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecl
Register PUT request.
Req type should be a struct, where all fields are automatically mapped from the request using 'json' tag or 'form' tag (for form-data, query param) or 'header' tag (only supports string/*string).
Res type should be a struct. By default both Res value and error (if not nil) will be wrapped inside miso.Resp and serialized to json. Wrapping to miso.Resp is customizable using miso.SetResultBodyBuilder func.
With both Req and Res type declared, miso will automatically parse these two types using reflect and generate an API documentation describing the endpoint.
func NewLazyRouteDecl ¶ added in v0.0.23
func NewLazyRouteDecl(url string, method string, handler func(c *gin.Context)) *LazyRouteDecl
func Post ¶
func Post[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecl
Register POST request.
The result and error are automatically wrapped to miso.Resp (see miso.SetResultBodyBuilder func) and serialized to json.
func Put ¶
func Put[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecl
Register PUT request.
The result and error are automatically wrapped to miso.Resp (see miso.SetResultBodyBuilder func) and serialized to json.
func RawDelete ¶
func RawDelete(url string, handler RawTRouteHandler) *LazyRouteDecl
Register DELETE request route (raw version)
func RawGet ¶
func RawGet(url string, handler RawTRouteHandler) *LazyRouteDecl
Register GET request route (raw version)
func RawPost ¶
func RawPost(url string, handler RawTRouteHandler) *LazyRouteDecl
Register POST request route (raw version)
func RawPut ¶
func RawPut(url string, handler RawTRouteHandler) *LazyRouteDecl
Register PUT request route (raw version)
func (*LazyRouteDecl) Desc ¶ added in v0.0.23
func (g *LazyRouteDecl) Desc(desc string) *LazyRouteDecl
Add endpoint description (only serves as metadata that maybe used by some plugins).
func (*LazyRouteDecl) DocHeader ¶ added in v0.0.23
func (g *LazyRouteDecl) DocHeader(headerName string, desc string) *LazyRouteDecl
Document header parameter that the endpoint will use (only serves as metadata that maybe used by some plugins).
func (*LazyRouteDecl) DocHeaderReq ¶ added in v0.0.26
func (g *LazyRouteDecl) DocHeaderReq(v any) *LazyRouteDecl
Document header parameters that the endpoint expects (only serves as metadata that maybe used by some plugins).
func (*LazyRouteDecl) DocJsonReq ¶ added in v0.0.23
func (g *LazyRouteDecl) DocJsonReq(v any) *LazyRouteDecl
Document json request that the endpoint expects (only serves as metadata that maybe used by some plugins).
func (*LazyRouteDecl) DocJsonResp ¶ added in v0.0.23
func (g *LazyRouteDecl) DocJsonResp(v any) *LazyRouteDecl
Document json response that the endpoint returns (only serves as metadata that maybe used by some plugins).
func (*LazyRouteDecl) DocQueryParam ¶ added in v0.0.23
func (g *LazyRouteDecl) DocQueryParam(queryName string, desc string) *LazyRouteDecl
Document query parameter that the endpoint will use (only serves as metadata that maybe used by some plugins).
func (*LazyRouteDecl) DocQueryReq ¶ added in v0.0.25
func (g *LazyRouteDecl) DocQueryReq(v any) *LazyRouteDecl
Document query parameters that the endpoint expects (only serves as metadata that maybe used by some plugins).
func (*LazyRouteDecl) Extra ¶ added in v0.0.23
func (g *LazyRouteDecl) Extra(key string, value any) *LazyRouteDecl
Add extra info to endpoint's metadata.
func (*LazyRouteDecl) Prepend ¶ added in v0.0.23
func (g *LazyRouteDecl) Prepend(baseUrl string)
func (*LazyRouteDecl) Protected ¶ added in v0.0.23
func (g *LazyRouteDecl) Protected() *LazyRouteDecl
Documents that the endpoint requires protection (only serves as metadata that maybe used by some plugins).
func (*LazyRouteDecl) Public ¶ added in v0.0.23
func (g *LazyRouteDecl) Public() *LazyRouteDecl
Mark endpoint publicly accessible (only serves as metadata that maybe used by some plugins).
func (*LazyRouteDecl) Resource ¶ added in v0.0.23
func (g *LazyRouteDecl) Resource(resource string) *LazyRouteDecl
Record the resource that the endppoint should be bound to (only serves as metadata that maybe used by some plugins).
type LocalCache ¶
Simple local map-based cache.
This should not be a long-live object.
func NewLocalCache ¶
func NewLocalCache[T any]() LocalCache[T]
create new LocalCache with key of type string and value of type T.
type MappedTRouteHandler ¶
Traced and parameters mapped route handler.
Req type should be a struct, where all fields are automatically mapped from the request using 'json' tag or 'form' tag (for form-data, query param) or 'header' tag (only supports string/*string).
Res type should be a struct. By default both Res value and error (if not nil) will be wrapped inside miso.Resp and serialized to json. Wrapping to miso.Resp is customizable using miso.SetResultBodyBuilder func.
With both Req and Res type declared, miso will automatically parse these two types using reflect and generate an API documentation describing the endpoint.
type MetricsCollector ¶ added in v0.0.13
type MetricsCollector struct { Desc []metrics.Description Samples []metrics.Sample SampleMap map[string]*metrics.Sample // contains filtered or unexported fields }
Collector of runtime/metrics.
Use NewMetricsCollector() to create a new collector, the collector is thread-safe. Periodically call Read() to load metrics from runtime. Once the metrics are loaded, you can either use Value() or MemStats() func to access the values that you are interested in.
func NewMetricsCollector ¶ added in v0.0.13
func NewMetricsCollector(descs []metrics.Description) MetricsCollector
Create new MetricsCollector.
MetricsCollector only supports Uint64 metrics, those that are not Uint64 kind, are simply ignored.
func (*MetricsCollector) MemStats ¶ added in v0.0.13
func (m *MetricsCollector) MemStats() runtime.MemStats
func (*MetricsCollector) Read ¶ added in v0.0.13
func (m *MetricsCollector) Read()
func (*MetricsCollector) Value ¶ added in v0.0.13
func (m *MetricsCollector) Value(name string) uint64
type MisoErr ¶ added in v0.0.3
type MisoErr struct { Code string // error code. Msg string // error message returned to the client requested to the endpoint. InternalMsg string // internal message that is only logged on server. }
Miso Error.
Use NewErrf(...) to instantiate.
func (*MisoErr) Is ¶ added in v0.0.25
Implements *MisoErr Is check.
Returns true, if both are *MisoErr and the code matches.
WithInternalMsg always create new error, so we can basically reuse the same error created using 'miso.NewErrf(...).WithCode(...)'
var ErrIllegalArgument = miso.NewErrf(...).WithCode(...) var e1 = ErrIllegalArgument.WithInternalMsg(...) var e2 = ErrIllegalArgument.WithInternalMsg(...) errors.Is(e1, ErrIllegalArgument) errors.Is(e2, ErrIllegalArgument)
type MsgListener ¶
type MsgListener struct { QueueName string Handler func(rail Rail, payload string) error NumOfRoutines int }
Message Listener for Queue
func (MsgListener) Concurrency ¶
func (m MsgListener) Concurrency() int
func (MsgListener) Queue ¶
func (m MsgListener) Queue() string
func (MsgListener) String ¶
func (m MsgListener) String() string
type MySQLBootstrapCallback ¶ added in v0.0.28
type MySQLConnParam ¶ added in v0.0.14
type NewRollingLogFileParam ¶
type OrderedShutdownHook ¶ added in v0.0.23
type OrderedShutdownHook struct { Hook func() Order int }
type PageRes ¶
type Paging ¶
type Paging struct { Limit int `json:"limit" desc:"page limit"` Page int `json:"page" desc:"page number, 1-based"` Total int `json:"total" desc:"total count"` }
func (Paging) ToRespPage ¶
type PostJobHook ¶ added in v0.0.8
type PostJobHook func(rail Rail, inf JobInf, stats JobExecStats) error
Hook triggered after job's execution.
type PreJobHook ¶ added in v0.0.8
Hook triggered before job's execution.
type PropagationKeys ¶
type PropagationKeys struct {
// contains filtered or unexported fields
}
type QueryPageParam ¶
type QueryPageParam[V any] struct { // contains filtered or unexported fields }
Create param for page query.
func NewPageQuery ¶ added in v0.0.26
func NewPageQuery[Res any]() *QueryPageParam[Res]
func (*QueryPageParam[V]) ForEach ¶
func (q *QueryPageParam[V]) ForEach(t Transform[V]) *QueryPageParam[V]
func (*QueryPageParam[V]) WithBaseQuery ¶ added in v0.0.26
func (q *QueryPageParam[V]) WithBaseQuery(qry PageQueryBuilder) *QueryPageParam[V]
func (*QueryPageParam[V]) WithPage ¶ added in v0.0.26
func (q *QueryPageParam[V]) WithPage(p Paging) *QueryPageParam[V]
func (*QueryPageParam[V]) WithSelectQuery ¶ added in v0.0.26
func (q *QueryPageParam[V]) WithSelectQuery(qry PageQueryBuilder) *QueryPageParam[V]
type QueueRegistration ¶
type RCache ¶
type RCache[T any] struct { ValueSerializer Serializer // serializer / deserializer // contains filtered or unexported fields }
Redis Cache implementation.
RCache internal isn't backed by an actual redis HSet. Cache name is simply the prefix for each key, and each key is stored independently.
Use NewRCache(...) to instantiate.
type RCacheConfig ¶ added in v0.0.8
type RCacheConfig struct { //expire time for each entry Exp time.Duration // Disable use of distributed lock to synchronize access to the key in the cache. // // Most of the operations are atomic except Get(...) with supplier callback. // If your are loading the cache manually using Put(...), then you probably don't need synchronization at all. NoSync bool }
Configuration of RCache.
type RLock ¶ added in v0.0.3
type RLock struct {
// contains filtered or unexported fields
}
RLock
func NewCustomRLock ¶ added in v0.0.3
func NewCustomRLock(rail Rail, key string, config RLockConfig) *RLock
Create customized RLock.
func NewRLock ¶ added in v0.0.3
Create new RLock with default backoff configuration (5ms backoff window, 1000 attempts, i.e., retry for 5s).
type RLockConfig ¶ added in v0.0.3
type RLockConfig struct { // Backoff duration. // // This is not an exact configuration. Linear back off strategy is used with a window size of 5ms, which means RLock will attempt to acquire the lock every 5ms. // // The number of times we may attempt to acquire the lock is called steps, which is by default 200 (that's 1s = 200 * 5ms). // When BackoffDuration is provided, this duration is divided by 5ms to convert to steps and then used by RLock. BackoffDuration time.Duration }
RLock Configuration.
type RString ¶
type RString []rune
func (RString) IfBlankThen ¶
if r is blank return defStr else return r
func (RString) SubstrStart ¶
substring starting from start
type RWMap ¶ added in v0.0.6
Map with sync.RWMutex embeded.
type RabbitListener ¶
type RabbitListener interface { Queue() string // return name of the queue Handle(rail Rail, payload string) error // handle message Concurrency() int }
RabbitListener of Queue
type Rail ¶
type Rail struct {
// contains filtered or unexported fields
}
Rail, an object that carries trace infromation along with the execution.
func BuildRail ¶
Build Rail from gin.Context.
This func creates new Rail for the first time by setting up proper traceId and spanId.
It can also recognize that a traceId (and spanId) was previously created, and do attempt to reuse these tracing values, such that the Rail acts as if it's the previous one, this is especially useful when we are recovering from a panic. In most cases, we should only call BuildRail for once.
However, if the Rail has attempted to overwrite it's spanId (i.e., creating new span), this newly created spanId will not be reflected on the Rail created here. But this should be fine, because new span is usually created for async operation.
func (Rail) WithCancel ¶
func (r Rail) WithCancel() (Rail, context.CancelFunc)
Create new Rail with context's CancelFunc
type RawTRouteHandler ¶
type RawTRouteHandler func(inb *Inbound)
Raw version of traced route handler.
type RedisConnParam ¶
type Resp ¶
type Resp struct { ErrorCode string `json:"errorCode" desc:"error code"` Msg string `json:"msg" desc:"message"` Error bool `json:"error" desc:"whether the request was successful"` Data interface{} `json:"data" desc:"response data"` }
Web Endpoint's Resp
type RespUnwrapper ¶ added in v0.0.25
type RespUnwrapper interface {
Unwrap() Resp
}
type ResultBodyBuilder ¶ added in v0.0.8
type ResultBodyBuilder struct { // wrap error in json, the returned object will be serialized to json. ErrJsonBuilder func(rail Rail, url string, err error) any // wrap payload object, the returned object will be serialized to json. PayloadJsonBuilder func(payload any) any // build empty ok response object, the returned object will be serialized to json. OkJsonBuilder func() any }
type RoutingGroup ¶ added in v0.0.4
func BaseRoute ¶ added in v0.0.4
func BaseRoute(baseUrl string) *RoutingGroup
Group routes together to share the same base url.
func GroupRoute ¶ added in v0.0.23
func GroupRoute(baseUrl string, grouped ...TreePath) *RoutingGroup
Group routes together to share the same base url.
func (*RoutingGroup) Group ¶ added in v0.0.4
func (rg *RoutingGroup) Group(grouped ...TreePath) *RoutingGroup
Group routes, routes are immediately registered
func (*RoutingGroup) Prepend ¶ added in v0.0.23
func (rg *RoutingGroup) Prepend(baseUrl string)
type Serializer ¶ added in v0.0.18
Value serializer / deserializer.
type Server ¶ added in v0.0.14
func SelectAnyServer ¶ added in v0.0.22
Select one Server randomly.
This func internally calls SelectServer with RandomServerSelector.
func SelectServer ¶ added in v0.0.14
Select one Server based on the provided selector.
GetServerList() is internally called to obtain current ServerList implementation.
If none is found and the service is not subscribed yet in the ServerList, this func subscribes to the service and polls the service instances immediately.
If ServerList indeed doesn't find any available instance for the service, ErrServiceInstanceNotFound is returned.
func (*Server) ServerAddress ¶ added in v0.0.14
Build server address with host and port concatenated, e.g., 'localhost:8080'
type ServerChangeListenerMap ¶ added in v0.0.19
func (*ServerChangeListenerMap) SubscribeChange ¶ added in v0.0.28
func (s *ServerChangeListenerMap) SubscribeChange(name string, cbk func())
func (*ServerChangeListenerMap) TriggerListeners ¶ added in v0.0.28
func (s *ServerChangeListenerMap) TriggerListeners(name string)
type ServerList ¶ added in v0.0.14
type ServerList interface { PollInstances(rail Rail) error PollInstance(rail Rail, name string) error ListServers(rail Rail, name string) []Server IsSubscribed(rail Rail, service string) bool Subscribe(rail Rail, service string) error Unsubscribe(rail Rail, service string) error UnsubscribeAll(rail Rail) error }
type ServerListServiceRegistry ¶ added in v0.0.28
type ServerListServiceRegistry struct {
Rule ServerSelector
}
func (ServerListServiceRegistry) ListServers ¶ added in v0.0.28
func (c ServerListServiceRegistry) ListServers(rail Rail, service string) ([]Server, error)
func (ServerListServiceRegistry) ResolveUrl ¶ added in v0.0.28
type ServerSelector ¶ added in v0.0.14
Server selector, returns index of the selected one.
type ServiceRegistry ¶
type ServiceRegistry interface { ResolveUrl(rail Rail, service string, relativeUrl string) (string, error) ListServers(rail Rail, service string) ([]Server, error) }
func GetServiceRegistry ¶
func GetServiceRegistry() ServiceRegistry
Get service registry.
Service registry initialization is lazy, don't store the retunred value in global var.
type Set ¶
type Set[T comparable] struct { // Keys in Set Keys map[T]Void }
Set data structure
It's internally backed by a Map.
To create a new Set, use NewSet() func.
type TBucket ¶ added in v0.0.22
type TBucket[T any] struct { // contains filtered or unexported fields }
func NewTBucket ¶ added in v0.0.22
type TClient ¶
type TClient struct { Url string // request url (absolute or relative) Headers map[string][]string // request headers Ctx context.Context // context provided by caller QueryParam map[string][]string // query parameters Rail Rail // rail // contains filtered or unexported fields }
Helper type for sending HTTP requests
Provides convenients methods to build requests, use http.Client and propagate tracing information
func NewDynTClient ¶
Create new defualt TClient with EnableServiceDiscovery(), EnableTracing(), and Require2xx() turned on.
The provided relUrl should be a relative url starting with '/'.
func (*TClient) AddHeader ¶
Append header, subsequent method calls doesn't override previously appended headers
func (*TClient) AddHeaders ¶
Append headers, subsequent method calls doesn't override previously appended headers
func (*TClient) AddQueryParams ¶
Append Query Parameters, subsequent method calls doesn't override previously appended parameters
func (*TClient) EnableServiceDiscovery ¶
Enable service discovery
func (*TClient) EnableTracing ¶
Enable tracing by putting propagation key/value pairs on http headers.
func (*TClient) Http ¶ added in v0.0.5
Append 'http://' protocol.
If service discovery is enabled, or the url contains http protocol already, this will be skipped.
func (*TClient) Https ¶ added in v0.0.5
Append 'https://' protocol.
If service discovery is enabled, or the url contains http protocol already, this will be skipped.
func (*TClient) PostJson ¶
Send POST request with JSON.
Use simple types like struct instad of pointer for body.
func (*TClient) Require2xx ¶ added in v0.0.8
Requires response to have 2xx status code, if not, the *TResponse will contain error built for this specific reason.
func (*TClient) SetContentType ¶
Set Content-Type
func (*TClient) SetHeaders ¶
Overwrite header
type TResponse ¶
type TResponse struct { Rail Rail Ctx context.Context Resp *http.Response RespHeader http.Header StatusCode int Err error }
Helper type for handling HTTP responses
func (*TResponse) Bytes ¶ added in v0.0.3
Read response as []bytes.
Response is always closed automatically.
If response body is somehow empty, *miso.NoneErr is returned.
func (*TResponse) Json ¶ added in v0.0.3
Read response as JSON object.
Response is always closed automatically.
If response body is somehow empty, *miso.NoneErr is returned.
func (*TResponse) Require2xx ¶
Check if it's 2xx, else return error
type TRouteHandler ¶
Traced route handler.
Res type should be a struct. By default both Res value and error (if not nil) will be wrapped inside miso.Resp and serialized to json. Wrapping to miso.Resp is customizable using miso.SetResultBodyBuilder func.
With Res type declared, miso will automatically parse the Res type using reflect and generate an API documentation describing the endpoint.
type TTLCache ¶ added in v0.0.3
type TTLCache[T any] interface { TryGet(key string) (T, bool) Get(key string, elseGet func() (T, bool)) (T, bool) Put(key string, t T) Del(key string) Size() int Exists(key string) bool PutIfAbsent(key string, t T) bool }
Time-based Cache.
func NewTTLCache ¶ added in v0.0.3
Create new TTLCache.
Each k/v is associated with a timestamp. Each time a key lookup occurs, it checks whether the k/v is still valid by comparing the timestamp with time.Now().
If the k/v is no longer 'alive', or the cache doesn't have the key, supplier func for the value is called, and the returned value is then cached. I.e., each k/v is evicted only at key lookup, there is no secret go-routine running to do the clean-up, the overhead for maintaining the cache is relatively small.
For the max size, TTLCache will try it's best to maintain it, but it's quite possible that all values in the cache are 'alive'. Whenever the max size is violated, the cache will simply drop the 'least recently put' item.
The returned TTLCache can be used concurrently.
type TagRetriever ¶
type TickRunner ¶ added in v0.0.14
type TickRunner struct {
// contains filtered or unexported fields
}
Runner that triggers run on every tick.
Create TickRunner using func NewTickRunner(...).
func NewTickRuner ¶ added in v0.0.14
func NewTickRuner(freq time.Duration, run func()) *TickRunner
func (*TickRunner) Start ¶ added in v0.0.14
func (t *TickRunner) Start()
func (*TickRunner) Stop ¶ added in v0.0.14
func (t *TickRunner) Stop()
type ValidationError ¶
Validation Error
func (*ValidationError) Error ¶
func (ve *ValidationError) Error() string
type VecTimer ¶ added in v0.0.13
type VecTimer struct {
// contains filtered or unexported fields
}
Timer based on prometheus.HistogramVec.
Duration is measured in millisecond.
Use NewVecTimer to create a new one, and each timer can only be used for once.
func NewVecTimer ¶ added in v0.0.13
func NewVecTimer(vec *prometheus.HistogramVec) *VecTimer
Create new timer that is back by prometheus HistogramVec. Each timer can only be used for once.
func (*VecTimer) ObserveDuration ¶ added in v0.0.13
type WalkTagCallback ¶ added in v0.0.26
Source Files ¶
- apidoc.go
- async.go
- auth.go
- bus.go
- cache.go
- cli.go
- client.go
- collection.go
- config.go
- consul.go
- convert.go
- ctx.go
- discovery.go
- err.go
- file.go
- func.go
- health.go
- ip.go
- json.go
- jwt.go
- logger.go
- math.go
- metrics.go
- mysql.go
- page.go
- perf.go
- prom.go
- prop.go
- rabbitmq.go
- random.go
- rcache.go
- redis.go
- reflect.go
- resp.go
- rlock.go
- rsa.go
- schedule.go
- server.go
- serverperf.go
- snowflake.go
- sqlite.go
- string.go
- task.go
- template.go
- time.go
- trace.go
- unsafe.go
- validation.go
- value.go
- version.go