Documentation
¶
Index ¶
- Constants
- Variables
- func AddAsyncShutdownHook(hook func())
- func AddBearerInterceptor(doIntercept func(method string, url string) bool, bearerToken func() string)
- func AddCorsAny()
- func AddGetPipelineDocFunc(f GetPipelineDocFunc)
- func AddHeaders(req *http.Request, headers map[string][]string)
- func AddHealthIndicator(hi HealthIndicator)
- func AddInterceptor(f func(inb *gin.Context, next func()))
- func AddOrderedAsyncShutdownHook(order int, hook func())
- func AddOrderedShutdownHook(order int, hook func())
- func AddPropagationKey(key string)
- func AddPropagationKeys(keys ...string)
- func AddShutdownHook(hook func())
- func AddXDesc(code string, desc string)
- func AppStoreGet[V any](app *MisoApp, k string) V
- func AppStoreGetElse[V any](app *MisoApp, k string, f func() V) V
- func ArgKeyVal(args []string) map[string][]string
- func AutoHandler[Req any, Res any](handler MappedTRouteHandler[Req, Res]) httpHandler
- func BearerAuth(delegate http.Handler, getExpectedToken func() string) http.HandlerFunc
- func BootstrapServer(args []string)
- func BuildRollingLogFileWriter(p NewRollingLogFileParam) *lumberjack.Logger
- func CatalogFetchServiceNames(rail Rail) (map[string][]string, error)
- func CatalogFetchServiceNodes(rail Rail, name string) ([]*api.CatalogService, error)
- func ChainValidationError(parentField string, e error) error
- func ChangeGetServerList(f func() ServerList)
- func CheckPortOpened(host string, port string, timeout time.Duration) error
- func ClientSkipTlsSecureCheck()
- func ConfigureLogging() error
- func ContainsProp(prop string) bool
- func CronExprEveryXHour(n int) string
- func CronExprEveryXMin(n int) string
- func CronExprEveryXSec(n int) string
- func CustomFormatter() logrus.Formatter
- func Debug(args ...interface{})
- func DebugTimeOp(r Rail, start time.Time, name string)
- func Debugf(format string, args ...interface{})
- func DefaultHealthCheckInbound(inb *Inbound)
- func DefaultMetricDesc(matcher *regexp.Regexp) []metrics.Description
- func DefaultReadConfig(args []string, rail Rail)
- func DefaultRecovery(c *gin.Context, e interface{})
- func DeregisterConsulService() error
- func DisableApidocEndpointRegister()
- func DisableDefaultHealthCheckHandler()
- func DisablePProfEndpointRegister()
- func DisablePrometheusBootstrap()
- func DispatchErrMsgJson(c *gin.Context, msg string)
- func DispatchJson(c *gin.Context, body interface{})
- func DispatchJsonCode(c *gin.Context, code int, body interface{})
- func EnableBasicAuth(f func(username string, password string, url string, method string) bool)
- func Error(args ...interface{})
- func ErrorStackTrace(err error) string
- func Errorf(format string, args ...interface{})
- func ExtractArgValue(args []string, predicate util.Predicate[string]) string
- func Fatal(args ...interface{})
- func Fatalf(format string, args ...interface{})
- func FilterMetricDesc(nameFilter func(name string) bool, ...) []metrics.Description
- 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 GetLogrusLogger() *logrus.Logger
- func GetPropAny(prop string) any
- func GetPropBool(prop string) bool
- func GetPropDur(prop string, unit time.Duration) time.Durationdeprecated
- func GetPropDuration(prop string) 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 GetPropStrTrimmed(prop string) string
- func GetPropagationKeys() []string
- func GuessConfigFilePath(args []string) string
- func HandleEndpointResult(inb Inbound, rail Rail, result any, err error)
- func HasProp(prop string) bool
- func HasScheduledJobs() bool
- func HttpAny(url string, handler RawTRouteHandler, extra ...util.StrPair)
- func Info(args ...interface{})
- func Infof(format string, args ...interface{})
- func InitAppModuleFunc[V any](initFunc func() V) func() V
- func InitConsulClient() error
- func IsConsulClientInitialized() bool
- func IsConsulServiceRegistered() bool
- func IsDebugLevel() bool
- func IsHealthcheckPass(rail Rail) bool
- func IsLogLevel(logLevel string) bool
- func IsNoneErr(err error) bool
- func IsProdMode() bool
- func IsShuttingDown() bool
- func IsTraceLevel() bool
- func JoinQueryParam(queryParams map[string][]string) string
- func LTimeOp(start time.Time, name string)
- func LoadConfigFromFile(configFile string, r Rail) error
- func LoadConfigFromReader(reader io.Reader, r Rail) error
- func LoadConfigFromStr(s string, r Rail) error
- func LoadPropagationKeys(r Rail)
- func MatchPathPatternFunc(patterns ...string) func(method string, url string) bool
- func MustBind(rail Rail, c *gin.Context, ptr any)
- func MustCompile(fs embed.FS, s string) *template.Template
- func NewDeleteRequest(url string) (*http.Request, error)
- func NewGetRequest(url string) (*http.Request, error)
- func NewHeadRequest(url string) (*http.Request, 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 NewReaderFile(reader io.Reader, name string) *readerFile
- func OnAppReady(f ...func(rail Rail) error)
- func OverwriteConf(args []string)
- func PTimeOp(start time.Time, name string)
- func ParseBearer(authorization string) (string, bool)
- func ParseLogLevel(logLevel string) (logrus.Level, bool)
- func PerfLogExclPath(path string)
- func PerfMiddleware() gin.HandlerFunc
- func PostJobExec(hook PostJobHook)
- func PostJson(url string, json string) (*http.Response, error)
- func PostServerBootstrap(f ...func(rail Rail) error)
- func PreConfiguredFormatter() logrus.Formatter
- func PreJobExec(hook PreJobHook)
- func PreProcessGin(preProcessor GinPreProcessor)
- func PreServerBootstrap(f ...func(rail Rail) error)
- func PrepareWebStaticFs(fs embed.FS, dir string)
- func PrometheusHandler() http.Handler
- func RandomServerSelector(servers []Server) int
- func RawAny(url string, handler RawTRouteHandler, extra ...util.StrPair)
- func RawHandler(handler RawTRouteHandler) httpHandler
- func RegisterAlias(alias, key string)
- func RegisterBootstrapCallback(c ComponentBootstrap)
- func RegisterConfigLoader(callback ...func(rail Rail) error)
- func RegisterConsulService() error
- func ReloadConfigFromReader(reader io.Reader) error
- func ReloadConfigFromStr(s ...string) error
- func ResHandler[Res any](handler TRouteHandler[Res]) httpHandler
- func ResolveArg(arg string) string
- func ResolveServerHost(address string) string
- func ScheduleCron(job Job) 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 SetErrLogHandler(handler ErrorLogHandler) bool
- func SetLogLevel(level string)
- func SetLogOutput(out io.Writer)
- func SetProp(prop string, val any)
- func SetResultBodyBuilder(rbb ResultBodyBuilder) error
- func Shutdown()
- func SprintMemStats(ms runtime.MemStats) string
- func SprintStats(ms runtime.MemStats, cs CpuStats) string
- func StartSchedulerAsync()
- func StartSchedulerBlocking()
- func StopScheduler()
- func SubscribeServerChanges(rail Rail, name string, cbk func()) error
- func TimeOp(r Rail, start time.Time, name 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 TriggerServerChangeListeners(service string)
- func UnknownErr(err error) error
- func UnknownErrMsgf(msg string, args ...any) error
- func UnknownErrf(err error, msg string, args ...any) error
- func UnmarshalFromProp(ptr any)
- func UnmarshalFromPropKey(key string, ptr any)
- func UnwrapErrStack(err error) (string, bool)
- func UsePropagationKeys(forEach func(key string))
- func Validate(target any) error
- func ValidateIntRule(ival int64, rule string, fname string, param string) error
- func ValidateRule(field reflect.StructField, value reflect.Value, rule string, ruleParam string) error
- func Warn(args ...interface{})
- func Warnf(format string, args ...interface{})
- func WrapErr(err error) error
- func WrapErrMulti(errs ...error) error
- func WrapErrf(err error, msg string, args ...any) error
- func WrapErrfCode(err error, code string, msg string, args ...any) error
- type AppConfig
- func (a *AppConfig) DefaultReadConfig(args []string)
- func (a *AppConfig) GetDefaultConfigFileLoaded() []string
- func (a *AppConfig) GetPropAny(prop string) any
- func (a *AppConfig) GetPropBool(prop string) bool
- func (a *AppConfig) GetPropDur(prop string, unit time.Duration) time.Durationdeprecated
- func (a *AppConfig) GetPropDuration(prop string) time.Duration
- func (a *AppConfig) GetPropInt(prop string) int
- func (a *AppConfig) GetPropIntSlice(prop string) []int
- func (a *AppConfig) GetPropStr(prop string) string
- func (a *AppConfig) GetPropStrMap(prop string) map[string]string
- func (a *AppConfig) GetPropStrSlice(prop string) []string
- func (a *AppConfig) GetPropStrTrimmed(prop string) string
- func (a *AppConfig) HasProp(prop string) bool
- func (a *AppConfig) IsProdMode() bool
- func (a *AppConfig) LoadConfigFromFile(configFile string) error
- func (a *AppConfig) LoadConfigFromReader(reader io.Reader) error
- func (a *AppConfig) LoadConfigFromStr(s string) error
- func (a *AppConfig) OverwriteConf(args []string)
- func (a *AppConfig) RegisterAlias(alias, key string)
- func (a *AppConfig) ReloadConfigFromReader(reader io.Reader) error
- func (a *AppConfig) ReloadConfigFromStr(sl ...string) error
- func (a *AppConfig) ResolveArg(arg string) string
- func (a *AppConfig) SetDefProp(prop string, defVal any)
- func (a *AppConfig) SetProp(prop string, val any)
- func (a *AppConfig) UnmarshalFromProp(ptr any)
- func (a *AppConfig) UnmarshalFromPropKey(key string, ptr any)
- func (a *AppConfig) WriteConfigAs(filename string) (err error)
- type CTFormatter
- type ComponentBootstrap
- 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 CpuStats
- type ErrorLog
- type ErrorLogHandler
- type FieldDesc
- type GetPipelineDocFunc
- type GinPreProcessor
- type GnResp
- type HealthIndicator
- type HealthStatus
- type HistTimer
- type HttpError
- type HttpProxy
- type HttpRoute
- 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) MustBind(ptr any)
- 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)
- func (i *Inbound) WriteJson(v any)
- func (i *Inbound) WriteJsonStatus(v any, httpStatus int)
- func (i *Inbound) WriteString(v string)
- type Job
- type JobExecStats
- type JobInf
- type JsonPayloadDesc
- type LazyRouteDecl
- func Delete[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecldeprecated
- func Get[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecldeprecated
- func HttpConnect(url string, handler httpHandler) *LazyRouteDecl
- func HttpDelete(url string, handler httpHandler) *LazyRouteDecl
- func HttpGet(url string, handler httpHandler) *LazyRouteDecl
- func HttpHead(url string, handler httpHandler) *LazyRouteDecl
- func HttpOptions(url string, handler httpHandler) *LazyRouteDecl
- func HttpPatch(url string, handler httpHandler) *LazyRouteDecl
- func HttpPost(url string, handler httpHandler) *LazyRouteDecl
- func HttpPut(url string, handler httpHandler) *LazyRouteDecl
- func HttpTrace(url string, handler httpHandler) *LazyRouteDecl
- func IDelete[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecldeprecated
- func IGet[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecldeprecated
- func IPost[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecldeprecated
- func IPut[Req any, Res any](url string, handler MappedTRouteHandler[Req, Res]) *LazyRouteDecldeprecated
- func Post[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecldeprecated
- func Put[Res any](url string, handler TRouteHandler[Res]) *LazyRouteDecldeprecated
- func RawConnect(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawDelete(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawGet(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawHead(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawOptions(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawPatch(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawPost(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawPut(url string, handler RawTRouteHandler) *LazyRouteDecl
- func RawTrace(url string, handler RawTRouteHandler) *LazyRouteDecldeprecated
- 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
- func (g *LazyRouteDecl) Scope(scope string) *LazyRouteDecl
- type LocalCache
- type MappedTRouteHandler
- type MetricsCollector
- type MisoApp
- func (a *MisoApp) AddAsyncShutdownHook(hook func())
- func (a *MisoApp) AddOrderedAsyncShutdownHook(order int, hook func())
- func (a *MisoApp) AddOrderedShutdownHook(order int, hook func())
- func (a *MisoApp) AddShutdownHook(hook func())
- func (a *MisoApp) Bootstrap(args []string)
- func (a *MisoApp) Config() *AppConfig
- func (a *MisoApp) IsShuttingDown() bool
- func (a *MisoApp) LoadConfig(args []string)
- func (a *MisoApp) OnAppReady(callback ...func(rail Rail) error)
- func (a *MisoApp) PostServerBootstrap(callback ...func(rail Rail) error)
- func (a *MisoApp) PreServerBootstrap(callback ...func(rail Rail) error)
- func (a *MisoApp) RegisterBootstrapCallback(bootstrapComponent ComponentBootstrap)
- func (a *MisoApp) RegisterConfigLoader(callback ...func(rail Rail) error)
- func (a *MisoApp) Shutdown()
- func (a *MisoApp) Store() *appStore
- type MisoErr
- func (e *MisoErr) Cause() error
- func (e *MisoErr) Code() string
- func (e *MisoErr) Error() string
- func (e *MisoErr) HasCode() bool
- func (e *MisoErr) InternalMsg() string
- func (e *MisoErr) Is(target error) bool
- func (e *MisoErr) Msg() string
- func (e *MisoErr) New() error
- func (e *MisoErr) StackTrace() string
- func (e *MisoErr) Unwrap() error
- func (e *MisoErr) WithCode(code string) *MisoErr
- func (e *MisoErr) WithInternalMsg(msg string, args ...any) *MisoErr
- func (e *MisoErr) WithMsg(msg string) *MisoErr
- func (e *MisoErr) Wrap(cause error) error
- func (e *MisoErr) Wrapf(cause error, internalMsg string, args ...any) error
- type NewRollingLogFileParam
- type OrderedShutdownHook
- type PageRes
- type Paging
- type ParamDoc
- type PipelineDoc
- type PlainStrFormatter
- type PostJobHook
- type PreJobHook
- type PropagationKeys
- type ProxyContext
- type ProxyFilter
- type ProxyHttpStatusError
- type ProxyTargetResolver
- 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) Done() <-chan struct{}
- func (r Rail) Error(args ...interface{})
- func (r Rail) ErrorIf(err error, op string, args ...any)
- 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) IsDone() bool
- 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) WarnIf(err error, op string, args ...any)
- 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
- func (r Rail) WithTimeout(timeout time.Duration) (Rail, context.CancelFunc)
- type RawTRouteHandler
- type Resp
- type RespUnwrapper
- type ResultBodyBuilder
- type RoutingGroup
- type Server
- type ServerChangeListenerMap
- type ServerList
- type ServerListServiceRegistry
- type ServerSelector
- type ServiceRegistry
- type SseReadConfig
- 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) LogBody() *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) PostFormData(data map[string]io.Reader) *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) PutForm(data url.Values) *TResponse
- func (t *TClient) PutFormData(data map[string]io.Reader) *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
- func (tr *TResponse) Bytes() ([]byte, error)
- func (tr *TResponse) Close() error
- func (tr *TResponse) Is2xx() bool
- func (tr *TResponse) Json(ptr any) error
- func (tr *TResponse) Require2xx() error
- func (tr *TResponse) Sse(parse func(e sse.Event) (stop bool, err error), ...) error
- func (tr *TResponse) Str() (string, error)
- func (tr *TResponse) WriteTo(writer io.Writer) (int64, error)
- type TResponseJsonCheckErr
- type TRouteHandler
- type TTLCache
- type TickRunner
- type TreePath
- type ValidationError
- type VecTimer
Constants ¶
const ( TagApiDocDesc = "desc" TagApiDocXDesc = "xdesc" )
const ( // Default shutdown hook execution order. DefShutdownOrder = 5 // 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 )
const ( // Zero value for empty serviceId ServiceIdNil = "nil" ServiceMetaRegisterTime = "miso-register_time" )
const ( ServiceStatusUp = "UP" ServiceStatusDown = "DOWN" )
const ( LOOPBACK_LOCALHOST = util.LoopbackLocalHost LOOPBACK_127 = util.Loopback127 LOCAL_IP_ANY = util.LocalIpAny )
Deprecated, use util.* instead.
const ( // misoconfig-prop: name of the application PropAppName = "app.name" // misoconfig-prop: warning threshold for slow ComponentBootstrap | 5s PropAppSlowBoostrapThresohold = "app.slow-bootstrap-threshold" // misoconfig-prop: whether production mode is turned on | true PropProdMode = "mode.production" // misoconfig-prop: extra config files that should be loaded PropConfigExtraFiles = "config.extra.files" )
misoconfig-section: Common Configuration
const ( // misoconfig-prop: enable http server | true PropServerEnabled = "server.enabled" // misoconfig-prop: http server host | 127.0.0.1 PropServerHost = "server.host" // misoconfig-prop: http server port | 8080 PropServerPort = "server.port" // misoconfig-prop: health check url | /health // misoconfig-alias: consul.healthCheckUrl | v0.2.0 PropHealthCheckUrl = "server.health-check-url" // misoconfig-prop: health check interval, it's only used for service discovery, e.g., Consul | 5s // misoconfig-alias: consul.healthCheckInterval | v0.2.0 PropHealthCheckInterval = "server.health-check-interval" // misoconfig-prop: health check timeout, it's only used for service discovery, e.g., Consul | 3s // misoconfig-alias: consul.healthCheckTimeout | v0.2.0 PropHealthcheckTimeout = "server.health-check-timeout" // misoconfig-prop: log all http server routes in INFO level | false PropServerLogRoutes = "server.log-routes" // misoconfig-prop: http server bearer authorization token for all endpoints | PropServerAuthBearer = "server.auth.bearer" // misoconfig-prop: time wait (in second) before whole app server shutdown (previously, before `v0.1.12`, it only applies to the http server) | 30 // misoconfig-alias: server.gracefulShutdownTimeSec | v0.2.0 PropServerGracefulShutdownTimeSec = "server.graceful-shutdown-time-sec" // misoconfig-prop: logs time duration for each inbound http request | false PropServerPerfEnabled = "server.perf.enabled" // misoconfig-prop: propagate trace info from inbound requests | true PropServerPropagateInboundTrace = "server.trace.inbound.propagate" // misoconfig-prop: enable inbound request parameter validation | true PropServerRequestValidateEnabled = "server.validate.request.enabled" // misoconfig-prop: enable server request log | false PropServerRequestLogEnabled = "server.request-log.enabled" // misoconfig-prop: enable pprof (exposed using endpoint '/debug/pprof'); in non-prod mode, it's always enabled | false PropServerPprofEnabled = "server.pprof.enabled" // misoconfig-prop: bearer token for pprof endpoints' authentication. however, if `server.auth.bearer` is set, this prop is ignored. PropServerPprofAuthBearer = "server.pprof.auth.bearer" // misoconfig-prop: generate api doc | true // misoconfig-alias: server.generate-endpoint-doc.enabled | v0.2.0 PropServerGenerateEndpointDocEnabled = "server.api-doc.enabled" // misoconfig-prop: build webpage for the generated api doc | true // misoconfig-alias: server.generate-endpoint-doc.web.enabled | v0.2.0 PropServerGenerateEndpointDocApiEnabled = "server.api-doc.web.enabled" // misoconfig-prop: generate markdown api doc to the specified file // misoconfig-alias: server.generate-endpoint-doc.file | v0.2.0 PropServerGenerateEndpointDocFile = "server.api-doc.file" // misoconfig-prop: the generated markdown api doc should exclude miso.TClient demo | false // misoconfig-alias: server.generate-endpoint-doc.file-excl-tclient-demo | v0.2.0 PropServerGenerateEndpointDocFileExclTClientDemo = "server.api-doc.file-excl-tclient-demo" // misoconfig-prop: the generated markdown api doc should exclude Angular HttpClient demo | false // misoconfig-alias: server.generate-endpoint-doc.file-excl-ng-client-demo | v0.2.0 PropServerGenerateEndpointDocFileExclNgClientDemo = "server.api-doc.file-excl-ngclient-demo" // misoconfig-prop: the generated markdown api doc should exclude openapi json for each endpoint | true // misoconfig-alias: server.generate-endpoint-doc.file-excl-openapi-spec | v0.2.0 PropServerGenerateEndpointDocFileExclOpenApi = "server.api-doc.file-excl-openapi-spec" // misoconfig-prop: the generated endpoint documentation should include app name as the path prefix | true // misoconfig-alias: server.generate-endpoint-doc.path-prefix-app | v0.2.0 PropServerGenerateEndpointDocInclPrefix = "server.api-doc.path-prefix-app" // misoconfig-prop: server address specified in openapi json doc | // misoconfig-alias: server.generate-endpoint-doc.openapi-spec.server | v0.2.0 PropServerGenerateEndpointDocOpenApiSpecServer = "server.api-doc.openapi-spec.server" // misoconfig-prop: path to generated openapi json for all endpoints | // misoconfig-alias: server.generate-endpoint-doc.openapi-spec.file | v0.2.0 PropServerGenerateEndpointDocOpenApiSpecFile = "server.api-doc.openapi-spec.file" // misoconfig-prop: path patterns for endpoints in openapi json (`slice of string`) | // misoconfig-alias: server.generate-endpoint-doc.openapi-spec.path-patterns | v0.2.0 PropServerGenerateEndpointDocOpenApiSpecPathPatterns = "server.api-doc.openapi-spec.path-patterns" // misoconfig-prop: automatically map header values to request struct | true PropServerRequestAutoMapHeader = "server.request.mapping.header" // misoconfig-prop: disable gin's builtin validation | true PropServerGinValidationDisabled = "server.gin.validation.disabled" PropServerActualPort = "server.actual-port" )
misoconfig-section: Web Server Configuration
const ( // misoconfig-prop: enable Consul client, service registration and service discovery | false PropConsulEnabled = "consul.enabled" // misoconfig-prop: registered service name | `"${app.name}"` // misoconfig-alias: consul.registerName | v0.2.0 PropConsuleRegisterName = "consul.register-name" // misoconfig-prop: registered service address | `"${server.host}"` // misoconfig-alias: consul.registerAddress | v0.2.0 PropConsulRegisterAddress = "consul.register-address" // misoconfig-prop: consul server address | localhost:8500 // misoconfig-alias: consul.consulAddress | v0.2.0 PropConsulAddress = "consul.consul-address" // misoconfig-prop: for how long the current instance is deregistered after first health check failure | 30m // misoconfig-alias: consul.healthCheckFailedDeregisterAfter | v0.2.0 PropConsulHealthCheckFailedDeregAfter = "consul.health-check-failed-deregister-time" // misoconfig-prop: fetch server list from Consul in ever N seconds | 30 // misoconfig-alias: consul.fetchServerInterval | v0.2.0 PropConsulFetchServerInterval = "consul.fetch-server-interval" // misoconfig-prop: enable endpoint for manual Consul service deregistration | false // misoconfig-alias: consul.enableDeregisterUrl | v0.2.0 PropConsulEnableDeregisterUrl = "consul.enable-deregister-url" // misoconfig-prop: endpoint url for manual Consul service deregistration | /consul/deregister // misoconfig-alias: consul.deregisterUrl | v0.2.0 PropConsulDeregisterUrl = "consul.deregister-url" // misoconfig-prop: instance metadata (`map[string]string`) PropConsulMetadata = "consul.metadata" )
misoconfig-section: Consul Configuration
const ( // misoconfig-prop: enable metrics collection using prometheus | true PropMetricsEnabled = "metrics.enabled" // misoconfig-prop: route used to expose collected metrics | /metrics PropMetricsRoute = "metrics.route" // misoconfig-prop: enable authorization for metrics endpoint | false PropMetricsAuthEnabled = "metrics.auth.enabled" // misoconfig-prop: bearer token for metrics endpoint authorization PropMetricsAuthBearer = "metrics.auth.bearer" // misoconfig-prop: enable job that logs memory and cpu stats periodically (using `runtime/metrics`) | false PropMetricsEnableMemStatsLogJob = "metrics.memstat.log.job.enabled" // misoconfig-prop: job cron expresson for memory stats log job | 0/30 * * * * * PropMetricsMemStatsLogJobCron = "metrics.memstat.log.job.cron" )
misoconfig-section: Metrics Configuration
const ( // misoconfig-prop: log level | info PropLoggingLevel = "logging.level" // misoconfig-prop: path to rolling log file PropLoggingRollingFile = "logging.rolling.file" // misoconfig-prop: logs are written to log file only | false PropLoggingRollingFileOnly = "logging.file.log-file-only" // misoconfig-prop: max age of log files in days, 0 means files are retained forever | 0 PropLoggingRollingFileMaxAge = "logging.file.max-age" // misoconfig-prop: max size of each log file (in mb) | 50 PropLoggingRollingFileMaxSize = "logging.file.max-size" // misoconfig-prop: max number of backup log files | 10 PropLoggingRollingFileMaxBackups = "logging.file.max-backups" // misoconfig-prop: rotate log file at every day 00:00 (local) | true PropLoggingRollingFileRotateDaily = "logging.file.rotate-daily" )
misoconfig-section: Logging Configuration
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, e.g., `valid:"notEmpty"` or `valid:"notEmpty:MyField is required"`. Supports string, array, slice, map. ValidNotNil = "notNil" // not nil, e.g., `valid:"notNil"` or `valid:"notNil:MyField is required"`. 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" ValidTrim = "trim" // trim string and *string value )
const ( ExtraName = "miso-Name" ExtraDesc = "miso-Desc" ExtraScope = "miso-Scope" ExtraResource = "miso-Resource" ExtraQueryParam = "miso-QueryParam" ExtraHeaderParam = "miso-HeaderParam" ExtraJsonRequest = "miso-JsonRequest" ExtraJsonResponse = "miso-JsonResponse" ExtraNgTable = "miso-NgTable" ScopePublic = "PUBLIC" ScopeProtected = "PROTECTED" TagQueryParam = "form" TagHeaderParam = "header" )
const (
Bearer = "Bearer"
)
const (
// Service registration status - passing.
ConsulStatusPassing = "passing"
)
const (
DefaultPageLimit = 30
)
const (
// misoconfig-prop: slice of service names that should be subcribed on startup
PropSDSubscrbe = "service-discovery.subscribe"
)
misoconfig-section: Service Discovery Configuration
const (
// misoconfig-prop: propagation keys in trace (string slice) |
PropTracingPropagationKeys = "tracing.propagation.keys"
)
misoconfig-section: Tracing Configuration
Variables ¶
var ( ErrMissingServiceName = Errf("service name is required") ErrServiceInstanceNotFound = Errf("unable to find any available service instance") ErrServerListNotFound = Errf("fail to find ServerList implemnetation") )
var ( ErrCodeGeneric string = "XXXX" ErrCodeUnknownError string = "UNKNOWN_ERROR" ErrCodeNotPermitted string = "NOT_PERMITTED" ErrCodeIllegalArgument string = "ILLEGAL_ARGUMENT" ErrUnknownError *MisoErr = NewErrf("Unknown Error").WithCode(ErrCodeUnknownError) ErrNotPermitted *MisoErr = NewErrf("Not Permitted").WithCode(ErrCodeNotPermitted) ErrIllegalArgument *MisoErr = NewErrf("Illegal Argument").WithCode(ErrCodeIllegalArgument) ErrServerShuttingDown *MisoErr = NewErrf("Server shutting down") )
var ( GetLocalIPV4 = util.GetLocalIPV4 IsLocalAddress = util.IsLocalAddress )
Deprecated, use util.* instead.
var ( GetCallerFn = getCallerFn GetCallerFnUpN = getCallerFnUpN )
var ( ValidateWalkTagCallbackDeprecated = util.WalkTagCallback{ Tag: TagValidationV1, OnWalked: validateOnWalked, } ValidateWalkTagCallback = util.WalkTagCallback{ Tag: TagValidationV2, OnWalked: validateOnWalked, } )
var (
ApiDocTypeAlias = map[string]string{
"ETime": "int64",
"*ETime": "int64",
"*util.ETime": "int64",
"util.ETime": "int64",
}
)
var (
Errf = NewErrf
)
var (
MetricsMemoryMatcher = regexp.MustCompile(`^/memory/.*`)
)
var (
MisoDefaultClient *http.Client
)
var PostServerBootstrapped = PostServerBootstrap
deprecated: use PostServerBootstrap(...) instead.
Functions ¶
func AddAsyncShutdownHook ¶ added in v0.1.25
func AddAsyncShutdownHook(hook func())
func AddBearerInterceptor ¶ added in v0.1.18
func AddCorsAny ¶ added in v0.1.19
func AddCorsAny()
func AddGetPipelineDocFunc ¶ added in v0.1.0
func AddGetPipelineDocFunc(f GetPipelineDocFunc)
Register func to supply PipelineDoc.
func AddHealthIndicator ¶ added in v0.0.6
func AddHealthIndicator(hi HealthIndicator)
Add health indicator.
func AddInterceptor ¶ added in v0.1.12
Add request interceptor.
For requests to be processed, next func must be called, otherwise the request is dropped (i.e., rejected).
For requests that are rejected, interceptor should set appropriate http status.
func AddOrderedAsyncShutdownHook ¶ added in v0.1.25
func AddOrderedAsyncShutdownHook(order int, hook func())
func AddOrderedShutdownHook ¶ added in v0.1.12
func AddOrderedShutdownHook(order int, hook func())
func AddPropagationKeys ¶ added in v0.0.27
func AddPropagationKeys(keys ...string)
Add propagation key for tracing
func AddShutdownHook ¶
func AddShutdownHook(hook func())
func AddXDesc ¶ added in v0.1.1
Associate xdesc value with the code appeared in field tag `xdesc:"..."`.
func AppStoreGet ¶ added in v0.1.12
func AppStoreGetElse ¶ added in v0.1.12
func AutoHandler ¶ added in v0.1.23
func AutoHandler[Req any, Res any](handler MappedTRouteHandler[Req, Res]) httpHandler
Create HTTP handler that automatically resolve Request and Response data.
Req type should be a struct (or a pointer to a struct), where all fields are automatically mapped from the request using 'json' tag, 'form' tag (for form-data or query param) or 'header' tag.
Both Res value and error (if not nil) are be wrapped inside miso.Resp and serialized as json. This behaviour can be custmized 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 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
miso.PreServerBootstrap(func(c Rail) error {
// do something right after configuration being loaded, but server hasn't been bootstraped yet
});
miso.PostServerBootstrap(func(c Rail) error {
// do something after the server bootstrap
});
// start the server
miso.BootstrapServer(os.Args)
func BuildRollingLogFileWriter ¶
func BuildRollingLogFileWriter(p NewRollingLogFileParam) *lumberjack.Logger
Create rolling file based logger
func CatalogFetchServiceNames ¶ added in v0.1.12
Fetch all registered services, this method always call Consul instead of reading from cache
func CatalogFetchServiceNodes ¶ added in v0.1.12
func CatalogFetchServiceNodes(rail Rail, name string) ([]*api.CatalogService, error)
Fetch registered service by name, this method always call Consul instead of reading from cache
func ChainValidationError ¶
func ChangeGetServerList ¶ added in v0.1.12
func ChangeGetServerList(f func() ServerList)
Change GetServiceList implmentation.
func CheckPortOpened ¶ added in v0.1.14
Check whether host's port is opened, connection is always closed.
func ClientSkipTlsSecureCheck ¶ added in v0.0.4
func ClientSkipTlsSecureCheck()
Disable TLS certificate check.
func ConfigureLogging ¶
func ConfigureLogging() error
Configure logging level and output target based on loaded configuration.
func CronExprEveryXHour ¶ added in v0.2.1
Build cron expression (with sceond field) for every X hours.
func CronExprEveryXMin ¶ added in v0.2.1
Build cron expression (with sceond field) for every X minutes.
func CronExprEveryXSec ¶ added in v0.2.1
Build cron expression (with sceond field) for every X seconds.
func DebugTimeOp ¶
Run timer for named operation and print result in log
e.g.,
defer DebugTimeOp(ec, time.Now(), "someOperation")
func DefaultHealthCheckInbound ¶ added in v0.2.0
func DefaultHealthCheckInbound(inb *Inbound)
Create a default health check endpoint that simply does 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 DisableApidocEndpointRegister ¶ added in v0.1.10
func DisableApidocEndpointRegister()
Disable apidoc endpoint handler.
func DisableDefaultHealthCheckHandler ¶ added in v0.1.10
func DisableDefaultHealthCheckHandler()
Disable the default health check endpoint handler.
func DisablePProfEndpointRegister ¶ added in v0.1.10
func DisablePProfEndpointRegister()
Disable pprof debug endpoint handler.
func DisablePrometheusBootstrap ¶ added in v0.1.10
func DisablePrometheusBootstrap()
Disable prometheus endpoint handler bootstrap.
func DispatchErrMsgJson ¶
deprecated: *gin.Context is leaky abstraction, use *miso.Inbound instead.
Dispatch error response in json format
func DispatchJson ¶
deprecated: *gin.Context is leaky abstraction, use *miso.Inbound instead.
Dispatch a json response
func DispatchJsonCode ¶ added in v0.0.18
deprecated: *gin.Context is leaky abstraction, use *miso.Inbound instead.
Dispatch a json response
func EnableBasicAuth ¶ added in v0.0.30
Enable Basic authorization globally for all registered endpoints.
func ErrorStackTrace ¶ added in v0.2.0
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 FilterMetricDesc ¶ added in v0.0.13
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 GetLogrusLogger ¶ added in v0.1.13
func GetPropDuration ¶ added in v0.2.1
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 GetPropStrTrimmed ¶ added in v0.1.30
Same as GetPropStr() except the returned string is trimmed
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 HasScheduledJobs ¶ added in v0.0.9
func HasScheduledJobs() bool
Whether scheduler is initialized
func HttpAny ¶ added in v0.1.23
func HttpAny(url string, handler RawTRouteHandler, extra ...util.StrPair)
func InitAppModuleFunc ¶ added in v0.1.12
func InitAppModuleFunc[V any](initFunc func() V) func() V
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 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 IsHealthcheckPass ¶ added in v0.1.10
Check health status, return true if all health check pass
func IsLogLevel ¶ added in v0.2.0
func IsTraceLevel ¶ added in v0.2.0
func IsTraceLevel() bool
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.
Calling this method overides previously loaded config.
func LoadConfigFromReader ¶ added in v0.0.29
Load config from io Reader.
It's the caller's responsibility to close the provided reader.
Calling this method overides previously loaded config.
func LoadConfigFromStr ¶ added in v0.1.1
Load config from string.
Calling this method overides previously loaded config.
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 MatchPathPatternFunc ¶ added in v0.1.22
func MustBind ¶
deprecated: *gin.Context is leaky abstraction, use *miso.Inbound instead.
Must bind request payload to the given pointer, else panic
func NewDeleteRequest ¶
Create DELETE request
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 NewReaderFile ¶ added in v0.1.18
func OnAppReady ¶ added in v0.2.1
Add listener that is invoked when server is ready.
OnAppReady(...) callbacks are invoked after PostServerBoostrap().
func OverwriteConf ¶ added in v0.0.31
func OverwriteConf(args []string)
Overwrite existing conf using environment and cli args.
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 PostServerBootstrap ¶ added in v0.1.12
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 PostServerBootstrap inside another PostServerBootstrap 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 PostServerBootstrap 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 PrometheusHandler ¶
Default handler for prometheus metrics.
func RandomServerSelector ¶ added in v0.0.14
Select Server randomly.
func RawAny ¶
func RawAny(url string, handler RawTRouteHandler, extra ...util.StrPair)
Register ANY request route (raw version)
Deprecated since v0.1.23, use miso.HttpAny() instead.
func RawHandler ¶ added in v0.1.23
func RawHandler(handler RawTRouteHandler) httpHandler
Create raw HTTP Handler.
Request and Response are handled by the handler itself.
func RegisterAlias ¶ added in v0.2.0
func RegisterAlias(alias, key string)
Register alias.
Only use this for backward compatibility.
E.g.,
miso.RegisterAlias(newKey, oldkey)
It may not work as expected if you are trying to call GetPropAny() on root node of a subtree.
func RegisterBootstrapCallback ¶
func RegisterBootstrapCallback(c 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 RegisterConfigLoader ¶ added in v0.2.0
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 ReloadConfigFromReader ¶ added in v0.1.28
Reload config from io Reader.
It's the caller's responsibility to close the provided reader.
Calling this method completely reloads previously loaded config.
func ReloadConfigFromStr ¶ added in v0.1.28
Reload config from string.
Calling this method completely reloads previously loaded config.
func ResHandler ¶ added in v0.1.23
func ResHandler[Res any](handler TRouteHandler[Res]) httpHandler
Create HTTP handler that automatically resolve Res.
Both Res value and error (if not nil) are be wrapped inside miso.Resp and serialized as json. This behaviour can be custmized using miso.SetResultBodyBuilder func.
With Res type declared, miso will automatically parse these the type using reflect and generate an API documentation describing the endpoint.
func ResolveServerHost ¶
Resolve server host, use IPV4 if the given address is empty or '0.0.0.0'
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 ServeTempl ¶ added in v0.0.29
func SetDefaultTimeout ¶ added in v0.0.6
Set default http client timeout
func SetErrLogHandler ¶ added in v0.0.33
func SetErrLogHandler(handler ErrorLogHandler) bool
Setup error log handler.
ErrorLogHnadler is invoked when ERROR level log is printed, the log messages passed to handler are buffered, but handler should never block for a long time (i.e., process as fast as possible). If the buffer is full, latest error log messages are simply dropped.
ErrorLogHandler can only be set once.
func SetLogLevel ¶ added in v0.0.8
func SetLogLevel(level string)
func SetLogOutput ¶ added in v0.1.13
func SetResultBodyBuilder ¶ added in v0.0.25
func SetResultBodyBuilder(rbb ResultBodyBuilder) error
Replace the default ResultBodyBuilder
func SprintMemStats ¶ added in v0.0.13
func StartSchedulerBlocking ¶
func StartSchedulerBlocking()
Start scheduler and block current routine
func SubscribeServerChanges ¶ added in v0.0.19
Subscribe to changes to service instances.
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 TriggerServerChangeListeners ¶ added in v0.1.12
func TriggerServerChangeListeners(service string)
Trigger service changes listeners.
func UnknownErr ¶ added in v0.1.16
Wrap an error to create new *MisoErr without any extra context.
This is almost equivalent to ErrUnknownError.Wrap(err)
If err is nil, nil is returned.
func UnknownErrMsgf ¶ added in v0.1.16
Equivalent to ErrUnknownError.WithInternalMsg(msg, args...).
func UnknownErrf ¶ added in v0.1.15
Equivalent to ErrUnknownError.Wrapf(..).
If err is nil, nil is returned.
func UnmarshalFromPropKey ¶ added in v0.0.22
Unmarshal configuration from a speicific key.
func UnwrapErrStack ¶ added in v0.1.13
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 ValidateRule ¶
func WrapErr ¶ added in v0.1.14
Wrap an error to create new *MisoErr with stacktrace.
If err is nil, nil is returned.
If err is *MisoErr, err is returned directly.
func WrapErrMulti ¶ added in v0.2.0
Wrap multi errors to create new *MisoErr with stacktrace.
If err is nil, nil is returned.
If err is *MisoErr, err is returned directly.
Types ¶
type AppConfig ¶ added in v0.1.12
type AppConfig struct {
// contains filtered or unexported fields
}
func (*AppConfig) DefaultReadConfig ¶ added in v0.1.12
Default way to read config file.
Normally, this func is called by *MisoApp. Use this only when it's necessary. and you should call this func only once.
The loaded configuration can be overriden by the cli arguments and environment variables.
func (*AppConfig) GetDefaultConfigFileLoaded ¶ added in v0.2.0
func (*AppConfig) GetPropAny ¶ added in v0.1.30
Get prop as any
func (*AppConfig) GetPropBool ¶ added in v0.1.12
Get prop as bool
func (*AppConfig) GetPropDuration ¶ added in v0.2.1
Get prop as time.Duration
func (*AppConfig) GetPropInt ¶ added in v0.1.12
Get prop as int
func (*AppConfig) GetPropIntSlice ¶ added in v0.1.12
Get prop as int slice
func (*AppConfig) GetPropStr ¶ added in v0.1.12
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 (*AppConfig) GetPropStrMap ¶ added in v0.1.12
Get prop as string based map.
func (*AppConfig) GetPropStrSlice ¶ added in v0.1.12
Get prop as string slice
func (*AppConfig) GetPropStrTrimmed ¶ added in v0.1.30
Same as GetPropStr() except the returned string is trimmed
func (*AppConfig) IsProdMode ¶ added in v0.1.12
Check whether we are running in production mode
func (*AppConfig) LoadConfigFromFile ¶ added in v0.1.12
Load config from file.
Calling this method overides previously loaded config.
func (*AppConfig) LoadConfigFromReader ¶ added in v0.1.12
Load config from io Reader.
It's the caller's responsibility to close the provided reader.
Calling this method overides previously loaded config.
func (*AppConfig) LoadConfigFromStr ¶ added in v0.1.12
Load config from string.
Calling this method overides previously loaded config.
func (*AppConfig) OverwriteConf ¶ added in v0.1.12
Overwrite existing conf using environment and cli args.
func (*AppConfig) RegisterAlias ¶ added in v0.2.0
func (*AppConfig) ReloadConfigFromReader ¶ added in v0.1.28
Reload config from io Reader.
It's the caller's responsibility to close the provided reader.
Calling this method completely reloads previously loaded config.
func (*AppConfig) ReloadConfigFromStr ¶ added in v0.1.28
Reload config from string.
Calling this method completely reloads previously loaded config.
func (*AppConfig) ResolveArg ¶ added in v0.1.12
Resolve argument, e.g., for arg like '${someArg}', it will in fact look for 'someArg' in os.Env
func (*AppConfig) SetDefProp ¶ added in v0.1.12
Set default value for the prop
func (*AppConfig) UnmarshalFromProp ¶ added in v0.1.12
Unmarshal configuration.
func (*AppConfig) UnmarshalFromPropKey ¶ added in v0.1.12
Unmarshal configuration from a speicific key.
func (*AppConfig) WriteConfigAs ¶ added in v0.1.24
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 0.
Order int
}
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 CpuStats ¶ added in v0.1.27
func CollectCpuStats ¶ added in v0.1.27
type ErrorLogHandler ¶ added in v0.0.33
type ErrorLogHandler func(el *ErrorLog)
type FieldDesc ¶ added in v0.1.11
type FieldDesc struct {
FieldName string // field name in golang
Name string // field name in json
TypeName string // type name in golang or type name alias translated
TypePkg string // pkg path of the type in golang
OriginTypeName string // type name in golang (reflect.Type.Name()) without import path
OriginTypeNameWithPkg string // type name in golang with import pkg
Desc string // `desc` tag value
JsonTag string // `json` tag value
Fields []FieldDesc // struct fields
// contains filtered or unexported fields
}
type GetPipelineDocFunc ¶ added in v0.1.0
type GetPipelineDocFunc func() []PipelineDoc
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 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 HttpProxy ¶ added in v0.1.10
type HttpProxy struct {
// contains filtered or unexported fields
}
Http Reverse Proxy.
HttpProxy by default use http.Client with 5s connect timeout and 30s response header timeout. In terms of connection reuse, the IdleConnTimeout is 5min, MaxIdleConns is 5, MaxIdleConnsPerHost is 100 and MaxConnsPerHost is 500.
func NewHttpProxy ¶ added in v0.1.10
func NewHttpProxy(proxiedPath string, targetResolver ProxyTargetResolver) *HttpProxy
Create HTTP proxy for specific path.
If proxiedPath is '/', then the default health check endpoint handler, promethues endpoint handler, pprof endpoint handler, and apidoc endpoint handler are all disabled to avoid path conflicts.
This func must be called before server bootstraps.
e.g., to create proxy path for /proxy/** and redirect all requests to localhost:8081.
// proxy all requests to /proxy* to server localhost:8081
_ = miso.NewHttpProxy("/proxy", func(proxyPath string) (string, error) {
return "http://localhost:8081" + proxyPath, nil
})
func (*HttpProxy) AddFilter ¶ added in v0.1.10
func (h *HttpProxy) AddFilter(f ProxyFilter)
func (*HttpProxy) ChangeClient ¶ added in v0.1.13
type HttpRoute ¶
type HttpRoute struct {
Url string // http request url.
Method string // http method.
Extra map[string][]any // extra metadata kv store.
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).
}
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 endpoint result handler.
The result or error is written back to the client. In most cases, caller must exit the handler after calling this method.
E.g.,
miso.HttpGet("/dir/info", miso.RawHandler(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)
}))
func (*Inbound) Unwrap ¶ added in v0.0.26
func (i *Inbound) Unwrap() (http.ResponseWriter, *http.Request)
func (*Inbound) WriteJsonStatus ¶ added in v0.1.21
func (*Inbound) WriteString ¶ added in v0.2.0
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 Rail) error // actual job execution logic.
LogJobExec bool // should job execution be logged, error msg is always logged regardless.
TriggeredOnBoostrapped bool // should job be triggered when server is fully bootstrapped
// contains filtered or unexported fields
}
type JobExecStats ¶ added in v0.0.8
type JsonPayloadDesc ¶ added in v0.1.9
func BuildJsonPayloadDesc ¶ added in v0.1.9
func BuildJsonPayloadDesc(v reflect.Value) JsonPayloadDesc
Parse value's type information to build json style description.
Only supports struct, pointer and slice.
type LazyRouteDecl ¶ added in v0.0.23
type LazyRouteDecl struct {
Url string
Method string
Handler func(c *gin.Context)
RegisterFunc func(extra ...util.StrPair)
Extras []util.StrPair
}
Lazy route declaration
func Delete
deprecated
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.
Deprecated: since v0.1.23, use miso.HttpDelete() instead.
func Get
deprecated
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.
Deprecated: since v0.1.23, use miso.HttpGet() instead.
func HttpConnect ¶ added in v0.1.23
func HttpConnect(url string, handler httpHandler) *LazyRouteDecl
func HttpDelete ¶ added in v0.1.23
func HttpDelete(url string, handler httpHandler) *LazyRouteDecl
func HttpGet ¶ added in v0.1.23
func HttpGet(url string, handler httpHandler) *LazyRouteDecl
func HttpHead ¶ added in v0.1.23
func HttpHead(url string, handler httpHandler) *LazyRouteDecl
func HttpOptions ¶ added in v0.1.23
func HttpOptions(url string, handler httpHandler) *LazyRouteDecl
func HttpPatch ¶ added in v0.1.23
func HttpPatch(url string, handler httpHandler) *LazyRouteDecl
func HttpPost ¶ added in v0.1.23
func HttpPost(url string, handler httpHandler) *LazyRouteDecl
func HttpPut ¶ added in v0.1.23
func HttpPut(url string, handler httpHandler) *LazyRouteDecl
func HttpTrace ¶ added in v0.1.23
func HttpTrace(url string, handler httpHandler) *LazyRouteDecl
func IDelete
deprecated
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.
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.
Deprecated: since v0.1.23, use miso.HttpDelete() instead.
func IGet
deprecated
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.
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.
Deprecated: since v0.1.23, use miso.HttpGet() instead.
func IPost
deprecated
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.
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.
Deprecated: since v0.1.23, use miso.HttpPost() instead.
func IPut
deprecated
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.
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.
Deprecated: since v0.1.23, use miso.HttpPut() instead.
func Post
deprecated
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.
Deprecated: since v0.1.23, use miso.HttpPost() instead.
func Put
deprecated
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.
Deprecated: since v0.1.23, use miso.HttpPut() instead.
func RawConnect ¶ added in v0.1.21
func RawConnect(url string, handler RawTRouteHandler) *LazyRouteDecl
Register CONNECT request route (raw version)
Deprecated since v0.1.23, use miso.HttpConnect() instead.
func RawDelete ¶
func RawDelete(url string, handler RawTRouteHandler) *LazyRouteDecl
Register DELETE request route (raw version)
Deprecated since v0.1.23, use miso.HttpDelete() instead.
func RawGet ¶
func RawGet(url string, handler RawTRouteHandler) *LazyRouteDecl
Register GET request route (raw version)
Deprecated since v0.1.23, use miso.HttpGet() instead.
func RawHead ¶ added in v0.1.21
func RawHead(url string, handler RawTRouteHandler) *LazyRouteDecl
Register HEAD request route (raw version)
Deprecated since v0.1.23, use miso.HttpHead() instead.
func RawOptions ¶ added in v0.1.21
func RawOptions(url string, handler RawTRouteHandler) *LazyRouteDecl
Register OPTIONS request route (raw version)
Deprecated since v0.1.23, use miso.HttpOptions() instead.
func RawPatch ¶ added in v0.1.21
func RawPatch(url string, handler RawTRouteHandler) *LazyRouteDecl
Register PATCH request route (raw version)
Deprecated since v0.1.23, use miso.HttpPatch() instead.
func RawPost ¶
func RawPost(url string, handler RawTRouteHandler) *LazyRouteDecl
Register POST request route (raw version)
Deprecated since v0.1.23, use miso.HttpPost() instead.
func RawPut ¶
func RawPut(url string, handler RawTRouteHandler) *LazyRouteDecl
Register PUT request route (raw version)
Deprecated since v0.1.23, use miso.HttpPut() instead.
func RawTrace
deprecated
added in
v0.1.21
func RawTrace(url string, handler RawTRouteHandler) *LazyRouteDecl
Register CONNECT ACE est route (raw version)
Deprecated: since v0.1.23, use miso.HttpTrace() instead.
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).
func (*LazyRouteDecl) Scope ¶ added in v0.1.4
func (g *LazyRouteDecl) Scope(scope string) *LazyRouteDecl
Document the access scope of the endpoint (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.
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 MisoApp ¶ added in v0.1.12
type MisoApp struct {
// contains filtered or unexported fields
}
func App ¶ added in v0.1.12
func App() *MisoApp
Get global miso app.
Only one MisoApp is supported, this func always returns the same app.
func (*MisoApp) AddAsyncShutdownHook ¶ added in v0.1.25
func (a *MisoApp) AddAsyncShutdownHook(hook func())
func (*MisoApp) AddOrderedAsyncShutdownHook ¶ added in v0.1.25
func (*MisoApp) AddOrderedShutdownHook ¶ added in v0.1.12
func (*MisoApp) AddShutdownHook ¶ added in v0.1.12
func (a *MisoApp) AddShutdownHook(hook func())
func (*MisoApp) IsShuttingDown ¶ added in v0.1.12
check if the server is shutting down
func (*MisoApp) LoadConfig ¶ added in v0.1.12
Load app configuration.
func (*MisoApp) OnAppReady ¶ added in v0.2.1
func (*MisoApp) PostServerBootstrap ¶ added in v0.1.12
func (*MisoApp) PreServerBootstrap ¶ added in v0.1.12
func (*MisoApp) RegisterBootstrapCallback ¶ added in v0.1.12
func (a *MisoApp) RegisterBootstrapCallback(bootstrapComponent ComponentBootstrap)
func (*MisoApp) RegisterConfigLoader ¶ added in v0.2.0
type MisoErr ¶ added in v0.0.3
type MisoErr struct {
// contains filtered or unexported fields
}
Miso Error.
Use NewErrf(...) to instantiate.
func NewErrfCode ¶ added in v0.2.1
Create new *MisoErr with message and error code.
func (*MisoErr) InternalMsg ¶ added in v0.0.3
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)
func (*MisoErr) StackTrace ¶ added in v0.1.14
func (*MisoErr) WithInternalMsg ¶ added in v0.0.22
type NewRollingLogFileParam ¶
type OrderedShutdownHook ¶ added in v0.0.23
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 PipelineDoc ¶ added in v0.0.33
type PlainStrFormatter ¶ added in v0.1.13
type PlainStrFormatter struct {
}
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 ProxyContext ¶ added in v0.1.10
type ProxyContext struct {
Rail *Rail
Inb *Inbound
ProxyPath string
// contains filtered or unexported fields
}
func (*ProxyContext) DelAttr ¶ added in v0.1.10
func (pc *ProxyContext) DelAttr(key string)
func (*ProxyContext) GetAttr ¶ added in v0.1.10
func (pc *ProxyContext) GetAttr(key string) (any, bool)
func (*ProxyContext) SetAttr ¶ added in v0.1.10
func (pc *ProxyContext) SetAttr(key string, val any)
type ProxyFilter ¶ added in v0.1.10
type ProxyFilter = func(pc *ProxyContext, next func())
type ProxyHttpStatusError ¶ added in v0.1.10
type ProxyHttpStatusError interface {
Status() int
}
type ProxyTargetResolver ¶ added in v0.1.10
Resolve proxy target path.
Proxy path may be empty string if root path is requested, otherwise, it should guarantee to contain a prefix slash.
returns ProxyHttpStatusError to respond a specific http status code.
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
func (Rail) WithTimeout ¶ added in v0.1.28
Create new Rail with timeout and context's CancelFunc
type RawTRouteHandler ¶
type RawTRouteHandler func(inb *Inbound)
Raw version of traced route handler.
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 Server ¶ added in v0.0.14
func SelectAnyServer ¶ added in v0.0.22
Select one Server randomly.
func SelectServer ¶ added in v0.0.14
Select one Server based on the provided selector algorithm.
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
type ServerChangeListenerMap struct {
Listeners map[string][]func()
Pool *util.AsyncPool
sync.RWMutex
}
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 {
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
}
func GetServerList ¶ added in v0.0.28
func GetServerList() ServerList
Get ServerList, may return nil.
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 SseReadConfig ¶ added in v0.1.19
type SseReadConfig struct {
MaxEventSize int
}
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) PostFormData ¶ added in v0.1.16
Send POST request with urlencoded form data
Caller is responsible for closing all the reader.
func (*TClient) PostJson ¶
Send POST request with JSON.
Use simple types like struct instad of pointer for body.
func (*TClient) PutFormData ¶ added in v0.1.18
Send PUT request with urlencoded form data
Caller is responsible for closing all the reader.
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
// contains filtered or unexported fields
}
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 TResponseJsonCheckErr ¶ added in v0.1.19
type TResponseJsonCheckErr interface {
CheckErr() 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 // Register callback to be invoked when entry is evicted. // // Callback may be invoked with locks obtained, callback should not block currnet goroutine. // Callback should not call any method on TTLCache, deadlock is almost guaranteed. OnEvicted(f func(key string, t T)) Keys() []string }
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 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 ¶
type ValidationError struct {
Field string
Rule string
ValidationMsg string
CustomValidationMsg string
}
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.