miso

package
v0.4.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 2, 2026 License: Apache-2.0 Imports: 68 Imported by: 0

Documentation

Overview

core implementation for miso.

Index

Constants

View Source
const (
	TagApiDocDesc  = "desc"
	TagApiDocXDesc = "xdesc"
)
View Source
const (
	// Components like database that are essential and must be ready before anything else.
	//
	// Since v0.3.2, L1 was updated from -20 to -30.
	BootstrapOrderL1 = -30

	// Components that are bootstraped before the web server, such as metrics stuff.
	//
	// Since v0.3.2, L2 was updated from -15 to -20.
	BootstrapOrderL2 = -20

	// The web server or anything similar, bootstraping web server doesn't really mean that we will receive inbound requests.
	BootstrapOrderL3 = -10

	// Default bootstrap order 0.
	BootstrapOrderDefault = 0

	// 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.
	//
	// Since v0.3.2, L4 was updated from -5 to 10.
	BootstrapOrderL4 = 10
)
View Source
const (
	// Zero value for empty serviceId
	ServiceIdNil = "nil"

	ServiceMetaRegisterTime = "miso-register_time"
)
View Source
const (
	ErrCodeGeneric            string = errs.ErrCodeGeneric
	ErrCodeUnknownError       string = errs.ErrCodeUnknownError
	ErrCodeNotPermitted       string = errs.ErrCodeNotPermitted
	ErrCodeIllegalArgument    string = errs.ErrCodeIllegalArgument
	ErrCodeServerShuttingDown string = errs.ErrCodeServerShuttingDown
)
View Source
const (
	XTraceId  = flow.XTraceId
	XSpanId   = flow.XSpanId
	XUsername = flow.XUsername
)
View Source
const (
	ServiceStatusUp   = "UP"
	ServiceStatusDown = "DOWN"
)
View Source
const (

	// misoconfig-prop: name of the application
	PropAppName = "app.name"

	// misoconfig-prop: profile name, it's only a flag used to identify which environment we are in
	PropAppProfile = "app.profile"

	// misoconfig-prop: warning threshold for slow ComponentBootstrap | 1s
	PropAppSlowBoostrapThresohold = "app.slow-bootstrap-threshold"

	// misoconfig-prop: stop app once ready, e.g., used to generate API doc. | false
	PropAppStopOnReady = "app.stop-on-ready"

	// 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"

	// whether we are in test env
	PropAppTestEnv = "app.test-env"
)

misoconfig-section: Common Configuration

View Source
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, '0' means select any port that can be used | 8080
	PropServerPort = "server.port"

	// misoconfig-prop: http server actual port used, read-only, do not overwrite it.
	// misoconfig-doc-only
	PropServerActualPort = "server.actual-port"

	// misoconfig-prop: http server route handler receives new context, i.e., if client disconnects, handler's context is not cancelled. | true
	PropServerHandlerWithNewContext = "server.handler.with-new-context"

	// 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 | true
	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 | true
	PropServerRequestLogEnabled = "server.request-log.enabled"

	// misoconfig-prop: enable apis for pprof (`/debug/pprof/**`) and flight recorder (`/debug/trace/**`), see [FlightRecorder Blog](https://go.dev/blog/flight-recorder); in non-prod mode, it's always enabled | false
	PropServerPprofEnabled = "server.pprof.enabled"

	// misoconfig-prop: bearer token for pprof and trace api authentication. If `server.auth.bearer` is set for all api, 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: file that contains the generated api doc golang demo
	PropServerApiDocGoFile = "server.api-doc.go.file"

	// misoconfig-prop: whether the generated api-doc golang demo file should compile | false
	PropServerApiDocGoCompileFile = "server.api-doc.go.compile-file"

	// misoconfig-prop: path patterns for endpoints that are written to api doc golang demo file
	PropServerApiDocGoPathPatterns = "server.api-doc.go.path-patterns"

	// misoconfig-prop: path patterns excluding for endpoints that should not be written to api doc golang demo file
	PropServerApiDocGoExclPathPatterns = "server.api-doc.go.excl-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"
)

misoconfig-section: Web Server Configuration

View Source
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

View Source
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

View Source
const (

	// misoconfig-prop: log level | info
	PropLoggingLevel = "logging.level"

	// misoconfig-prop: path to rolling log file
	PropLoggingRollingFile = "logging.rolling.file"

	// misoconfig-prop: append ip suffix to log file, e.g., myapp-192.168.1.1.log | false
	PropLoggingRollingFileAppendIpSuffix = "logging.file.append-ip-suffix"

	// 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, 0 means INF | 0
	PropLoggingRollingFileMaxBackups = "logging.file.max-backups"

	// misoconfig-prop: rotate log file at every day 00:00 (local) | true
	PropLoggingRollingFileRotateDaily = "logging.file.rotate-daily"

	// misoconfig-prop: list of logger name that rewrite DEBUG log to INFO log
	// misoconfig-doc-only
	PropLoggingLoggerDebugToInfo = "logging.logger.debug-to-info"
)

misoconfig-section: Logging Configuration

View Source
const (
	// misoconfig-prop: enable API to manually trigger jobs (and tasks on current node) | false
	PropSchedApiTriggerJobEnabled = "scheduler.api.trigger-job.enabled"

	// misoconfig-prop: cron scheduler time-zone name, e.g., `Europe/Paris`. | Local
	// misoconfig-doc-only
	PropSchedTimezone = "scheduler.time-zone"
)

misoconfig-section: Job Scheduler Configuration

View Source
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
)
View Source
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"
)
View Source
const (
	Bearer = "Bearer"
)
View Source
const (
	// Service registration status - passing.
	ConsulStatusPassing = "passing"
)
View Source
const (
	// Default shutdown hook execution order.
	DefShutdownOrder = 5
)
View Source
const (
	DefaultPageLimit = 30
)
View Source
const (

	// misoconfig-prop: slice of service names that should be subcribed on startup
	PropSDSubscrbe = "service-discovery.subscribe"
)

misoconfig-section: Service Discovery Configuration

View Source
const (

	// misoconfig-prop: propagation keys in trace (string slice) |
	PropTracingPropagationKeys = "tracing.propagation.keys"
)

misoconfig-section: Tracing Configuration

Variables

View Source
var (
	ApiDocGoSkipParsingTypes = []ApiDocFuzzType{
		{"github.com/curtisnewbie/miso/middleware/user-vault/common", "User"},
		{"github.com/curtisnewbie/miso/util/hash", "Set"},
		{"github.com/curtisnewbie/miso/util/hash", "SyncSet"},
		{"github.com/curtisnewbie/miso/middleware/money", "Amt"},
	}

	ApiDocTsSkipParsingTypes = []ApiDocFuzzType{
		{"github.com/curtisnewbie/miso/util/hash", "Set"},
		{"github.com/curtisnewbie/miso/util/hash", "SyncSet"},
		{"github.com/curtisnewbie/miso/middleware/money", "Amt"},
	}

	ApiDocNotInclTypes = []ApiDocFuzzType{
		{"github.com/curtisnewbie/miso/miso", "PageRes"},
		{"github.com/curtisnewbie/miso/miso", "Paging"},
	}

	ApiDocTypeAlias = map[string]string{
		"Time":         "int64",
		"*atom.Time":   "int64",
		"Set[any]":     "[]any",
		"Set[string]":  "[]string",
		"Set[int]":     "[]int",
		"Set[int32]":   "[]int32",
		"Set[int64]":   "[]int64",
		"Set[float32]": "[]float32",
		"Set[float64]": "[]float64",
		"*Time":        "int64",

		"*hash.Set[any]":     "[]any",
		"*hash.Set[string]":  "[]string",
		"*hash.Set[int]":     "[]int",
		"*hash.Set[int32]":   "[]int32",
		"*hash.Set[int64]":   "[]int64",
		"*hash.Set[float32]": "[]float32",
		"*hash.Set[float64]": "[]float64",
	}
)
View Source
var (
	ErrMissingServiceName      = errs.NewErrf("service name is required")
	ErrServiceInstanceNotFound = errs.NewErrf("unable to find any available service instance")
	ErrServerListNotFound      = errs.NewErrf("fail to find ServerList implemnetation")
)
View Source
var (
	ErrUnknownError       = errs.ErrUnknownError
	ErrNotPermitted       = errs.ErrNotPermitted
	ErrIllegalArgument    = errs.ErrIllegalArgument
	ErrServerShuttingDown = errs.ErrServerShuttingDown
)
View Source
var (
	// Deprecated: use [errs.NewErrf] instead.
	Errf            = errs.NewErrf
	NewErrf         = errs.NewErrf
	IsNoneErr       = errs.IsNoneErr
	NewErrfCode     = errs.NewErrfCode
	ErrfCode        = errs.NewErrfCode
	UnknownErr      = errs.UnknownErr
	WrapErr         = errs.Wrap
	WrapErrMulti    = errs.WrapErrMulti
	UnknownErrf     = errs.UnknownErrf
	UnknownErrMsgf  = errs.UnknownErrMsgf
	WrapErrf        = errs.Wrapf
	WrapErrfCode    = errs.WrapErrfCode
	UnwrapErrStack  = errs.UnwrapErrStack
	ErrorStackTrace = errs.ErrorStackTrace
)
View Source
var (
	GetCallerFn    = src.GetCallerFn
	GetCallerFnUpN = src.GetCallerFnUpN

	ConfigDebugLogToInfo      = flow.ConfigDebugLogToInfo
	EmptyRail                 = flow.EmptyRail
	NewTraceId                = flow.NewTraceId
	NewSpanId                 = flow.NewSpanId
	NewRail                   = flow.NewRail
	GetCtxStr                 = flow.GetCtxStr
	GetCtxInt                 = flow.GetCtxInt
	BuildRollingLogFileWriter = flow.BuildRollingLogFileWriter
	CustomFormatter           = flow.CustomFormatter
	PreConfiguredFormatter    = flow.PreConfiguredFormatter
	TraceLogger               = flow.TraceLogger
	IsDebugLevel              = flow.IsDebugLevel
	IsTraceLevel              = flow.IsTraceLevel
	IsLogLevel                = flow.IsLogLevel
	ParseLogLevel             = flow.ParseLogLevel
	SetLogLevel               = flow.SetLogLevel
	SetLogOutput              = flow.SetLogOutput
	GetLogrusLogger           = flow.GetLogrusLogger
	Infof                     = flow.Infof
	Tracef                    = flow.Tracef
	Debugf                    = flow.Debugf
	Warnf                     = flow.Warnf
	Errorf                    = flow.Errorf
	Fatalf                    = flow.Fatalf
	Debug                     = flow.Debug
	Info                      = flow.Info
	Warn                      = flow.Warn
	Error                     = flow.Error
	Fatal                     = flow.Fatal
	AddPropagationKeys        = flow.AddPropagationKeys
	AddPropagationKey         = flow.AddPropagationKey
	GetPropagationKeys        = flow.GetPropagationKeys
	UsePropagationKeys        = flow.UsePropagationKeys
	BuildTraceHeadersAny      = flow.BuildTraceHeadersAny
	BuildTraceHeadersStr      = flow.BuildTraceHeadersStr
)
View Source
var (
	ValidateWalkTagCallbackDeprecated = rfutil.WalkTagCallback{
		Tag:      TagValidationV1,
		OnWalked: validateOnWalked,
	}
	ValidateWalkTagCallback = rfutil.WalkTagCallback{
		Tag:      TagValidationV2,
		OnWalked: validateOnWalked,
	}
)
View Source
var (
	ErrFlightRecorderNotRunning = errs.NewErrfCode("FLIGHT_RECORDER_NOT_RUNNING", "FlightRecorder not running")
)
View Source
var (
	MetricsMemoryMatcher = regexp.MustCompile(`^/memory/.*`)
)
View Source
var (
	MisoDefaultClient *http.Client
)
View Source
var (
	NewTickRuner = async.NewTickRuner
)
View Source
var (
	// Error that represents None or Nil.
	//
	// Use miso.IsNoneErr(err) to check if an error represents None.
	NoneErr = errs.NoneErr
)

Functions

func AddAsyncShutdownHook added in v0.1.25

func AddAsyncShutdownHook(hook func())

func AddBearerAuthInterceptor added in v0.2.2

func AddBearerAuthInterceptor(doIntercept func(method string, url string) bool, validateBearerToken func(provided string) bool)

func AddBearerInterceptor deprecated added in v0.1.18

func AddBearerInterceptor(doIntercept func(method string, url string) bool, bearerToken func() string)

Deprecated: use AddBearerAuthInterceptor instead.

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 AddHeaders

func AddHeaders(req *http.Request, headers map[string][]string)

Add http headers

func AddHealthIndicator added in v0.0.6

func AddHealthIndicator(hi HealthIndicator)

Add health indicator.

func AddInterceptor added in v0.1.12

func AddInterceptor(f func(inb *gin.Context, next func()))

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 AddShutdownHook

func AddShutdownHook(hook func())

func AddXDesc added in v0.1.1

func AddXDesc(code string, desc string)

Associate xdesc value with the code appeared in field tag `xdesc:"..."`.

func AppStoreGet added in v0.1.12

func AppStoreGet[V any](app *MisoApp, k string) V

func AppStoreGetElse added in v0.1.12

func AppStoreGetElse[V any](app *MisoApp, k string, f func() V) V

func ArgKeyVal

func ArgKeyVal(args []string) map[string][]string

Parse CLI args to key-value map

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 BeforeWebRouteRegister added in v0.3.2

func BeforeWebRouteRegister(f ...func(Rail) error)

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 CatalogFetchServiceNames added in v0.1.12

func CatalogFetchServiceNames(rail Rail) (map[string][]string, error)

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 ChainValidationError(parentField string, e error) error

func ChangeDefaultConfigFilename added in v0.3.8

func ChangeDefaultConfigFilename(f string)

Change default config filename, by default it's conf.yml.

func ChangeGetServerList added in v0.1.12

func ChangeGetServerList(f func() ServerList)

Change GetServiceList implmentation.

func CheckPortOpened added in v0.1.14

func CheckPortOpened(host string, port string, timeout time.Duration) error

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 ContentTypeLoggable added in v0.3.5

func ContentTypeLoggable(contentType string) bool

func CronExprEveryXHour added in v0.2.1

func CronExprEveryXHour(n int) string

Build cron expression (with sceond field) for every X hours.

func CronExprEveryXMin added in v0.2.1

func CronExprEveryXMin(n int) string

Build cron expression (with sceond field) for every X minutes.

func CronExprEveryXSec added in v0.2.1

func CronExprEveryXSec(n int) string

Build cron expression (with sceond field) for every X seconds.

func DebugTimeOp

func DebugTimeOp(r Rail, start time.Time, name string, args ...any)

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

func DefaultReadConfig(args []string, rail Rail)

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 DefaultRecovery

func DefaultRecovery(c *gin.Context, e interface{})

Default Recovery func

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 EnableBasicAuth added in v0.0.30

func EnableBasicAuth(f func(username string, password string, url string, method string) bool)

Enable Basic authorization globally for all registered endpoints.

func ExtractArgValue

func ExtractArgValue(args []string, predicate func(t string) bool) string

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 FilterMetricDesc(nameFilter func(name string) bool, kindFilter func(kind metrics.ValueKind) bool) []metrics.Description

func FlightRecorder added in v0.4.0

func FlightRecorder() *flightRecorder

func FuzzMatchType added in v0.4.10

func FuzzMatchType(v interface {
	TypeInfo() (pkg string, typeName string)
}, against ApiDocFuzzType) bool

func FuzzMatchTypes added in v0.4.10

func FuzzMatchTypes(v interface {
	TypeInfo() (pkg string, typeName string)
}, against []ApiDocFuzzType) bool

func GetConsulClient

func GetConsulClient() *api.Client

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 GetEnv

func GetEnv(key string) string

Get environment variable

func GetEnvElse

func GetEnvElse(key string, defVal string) string

Get environment variable with default value

func GetPropAny added in v0.1.30

func GetPropAny(prop string) any

Get prop as any

func GetPropBool

func GetPropBool(prop string) bool

Get prop as bool

func GetPropBoolNf added in v0.4.11

func GetPropBoolNf(prop string, kv ...string) bool

func GetPropChild added in v0.2.13

func GetPropChild(prop string) []string

Get prop immediate child names

func GetPropDur deprecated added in v0.0.14

func GetPropDur(prop string, unit time.Duration) time.Duration

Get prop as time.Duration

Deprecated: Use GetPropDuration instead.

func GetPropDurNf added in v0.4.11

func GetPropDurNf(prop string, kv ...string) time.Duration

func GetPropDuration added in v0.2.1

func GetPropDuration(prop string) time.Duration

Get prop as time.Duration

func GetPropFloat added in v0.4.8

func GetPropFloat(prop string) float64

Get prop as int

func GetPropFloatNf added in v0.4.11

func GetPropFloatNf(prop string, kv ...string) float64

func GetPropInt

func GetPropInt(prop string) int

Get prop as int

func GetPropIntNf added in v0.4.11

func GetPropIntNf(prop string, kv ...string) int

func GetPropIntSlice

func GetPropIntSlice(prop string) []int

Get prop as int slice

func GetPropIntSliceNf added in v0.4.11

func GetPropIntSliceNf(prop string, kv ...string) []int

func GetPropStr

func GetPropStr(prop string) string

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

func GetPropStrMap(prop string) map[string]string

Get prop as string based map.

func GetPropStrNf added in v0.4.11

func GetPropStrNf(prop string, kv ...string) string

func GetPropStrSlice added in v0.0.3

func GetPropStrSlice(prop string) []string

Get prop as string slice

func GetPropStrSliceNf added in v0.4.11

func GetPropStrSliceNf(prop string, kv ...string) []string

func GetPropStrTrimmed added in v0.1.30

func GetPropStrTrimmed(prop string) string

Same as GetPropStr() except the returned string is trimmed

func GuessConfigFilePath

func GuessConfigFilePath(args []string) string

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'.

See ChangeDefaultConfigFilename.

func HandleEndpointResult added in v0.0.23

func HandleEndpointResult(inb Inbound, rail Rail, result any, err error)

Handle endpoint's result using the configured EndpointResultHandler.

func HandleFlightRecorderRun added in v0.3.3

func HandleFlightRecorderRun(inb *Inbound)

func HandleFlightRecorderSnapshot added in v0.4.0

func HandleFlightRecorderSnapshot(inb *Inbound)

func HandleFlightRecorderStop added in v0.3.3

func HandleFlightRecorderStop(inb *Inbound)

func HasProp

func HasProp(prop string) bool

Check whether the prop exists

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 ...pair.Pair[string, any])

func InTestEnv added in v0.4.11

func InTestEnv() bool

Check whether we are running in env bootstrapped by PrepareTestEnv.

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

func IsHealthcheckPass(rail Rail) bool

Check health status, return true if all health check pass

func IsProdMode

func IsProdMode() bool

Check whether we are running in production mode

func IsShuttingDown

func IsShuttingDown() bool

check if the server is shutting down

func JoinQueryParam

func JoinQueryParam(queryParams map[string][]string) string

Join query parameters

func LoadConfigFromFile

func LoadConfigFromFile(configFile string, r Rail) error

Load config from file.

Calling this method overides previously loaded config.

func LoadConfigFromReader added in v0.0.29

func LoadConfigFromReader(reader io.Reader, r Rail) error

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

func LoadConfigFromStr(s string, r Rail) error

Load config from string.

Calling this method overides previously loaded config.

func LoadPropagationKeys added in v0.0.7

func LoadPropagationKeys(r Rail)

Load propagation keys from configuration.

func LogJobNextRun added in v0.2.5

func LogJobNextRun(rail Rail, jobName string)

func MatchPathPatternFunc added in v0.1.22

func MatchPathPatternFunc(patterns ...string) func(method string, url string) bool

func MustCompile added in v0.0.29

func MustCompile(fs embed.FS, s string) *template.Template

func NewConnectRequest added in v0.2.2

func NewConnectRequest(url string) (*http.Request, error)

Create CONNECT request

func NewDeleteRequest

func NewDeleteRequest(url string) (*http.Request, error)

Create DELETE request

func NewGetRequest

func NewGetRequest(url string) (*http.Request, error)

Create GET request

func NewHeadRequest

func NewHeadRequest(url string) (*http.Request, error)

Create HEAD request

func NewOptionsRequest

func NewOptionsRequest(url string) (*http.Request, error)

Create OPTIONS request

func NewPatchRequest added in v0.2.2

func NewPatchRequest(url string) (*http.Request, error)

Create PATCH request

func NewPostRequest

func NewPostRequest(url string, body io.Reader) (*http.Request, error)

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

func NewPutRequest(url string, body io.Reader) (*http.Request, error)

Create PUT request

func NewReaderFile added in v0.1.18

func NewReaderFile(reader io.Reader, name string) *readerFile

func NewTraceRequest added in v0.2.2

func NewTraceRequest(url string) (*http.Request, error)

Create TRACE request

func OnAppReady added in v0.2.1

func OnAppReady(f ...func(rail Rail) error)

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 ParseBearer added in v0.0.13

func ParseBearer(authorization string) (string, bool)

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 PostJson

func PostJson(url string, json string) (*http.Response, error)

Send POST request

func PostServerBootstrap added in v0.1.12

func PostServerBootstrap(f ...func(rail Rail) error)

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 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

func PreServerBootstrap(f ...func(rail Rail) error)

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

func PrepareWebStaticFs(fs embed.FS, dir string, hostPrefix ...string)

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

func PrometheusHandler() http.Handler

Default handler for prometheus metrics.

func RandomServerSelector added in v0.0.14

func RandomServerSelector(servers []Server) int

Select Server randomly.

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 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 RegisterConfigLoader(callback ...func(rail Rail) error)

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.

func ReloadConfigFromReader added in v0.1.28

func ReloadConfigFromReader(reader io.Reader) error

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

func ReloadConfigFromStr(s ...string) error

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 ResolveArg

func ResolveArg(arg string) string

Resolve '${someArg}' style variables.

func ResolveServerHost

func ResolveServerHost(address string) string

Resolve server host, use IPV4 if the given address is empty or '0.0.0.0'

func ScheduleCron

func ScheduleCron(job Job) error

add a cron job to scheduler, note that the cron expression includes second, e.g., '*/1 * * * * *'

this func doesn't start the scheduler

func SendGet

func SendGet(url string, headers map[string][]string) (*http.Response, error)

Send GET request

func SendPost

func SendPost(url string, body io.Reader) (*http.Response, error)

Send POST request

func ServeStatic added in v0.0.29

func ServeStatic(inb *Inbound, fs embed.FS, file string)

func ServeTempl added in v0.0.29

func ServeTempl(inb *Inbound, fs embed.FS, tmplName string, data any)

func SetDefProp

func SetDefProp(prop string, defVal any)

Set default value for the prop

func SetDefaultTimeout added in v0.0.6

func SetDefaultTimeout(ttl time.Duration)

Set default http client timeout

func SetEnv

func SetEnv(key string, val string)

Set environment variable

func SetProp

func SetProp(prop string, val any)

Set value for the prop

func SetResultBodyBuilder added in v0.0.25

func SetResultBodyBuilder(rbb ResultBodyBuilder) error

Replace the default ResultBodyBuilder

func Shutdown

func Shutdown()

Shutdown server

func SprintMemStats added in v0.0.13

func SprintMemStats(ms runtime.MemStats) string

func SprintStats added in v0.1.27

func SprintStats(ms runtime.MemStats, cs CpuStats) string

func StartSchedulerAsync

func StartSchedulerAsync()

Start scheduler asynchronously

func StartSchedulerBlocking

func StartSchedulerBlocking()

Start scheduler and block current routine

func StopScheduler

func StopScheduler()

Stop scheduler

func SubscribeServerChanges added in v0.0.19

func SubscribeServerChanges(rail Rail, name string, cbk func()) error

Subscribe to changes to service instances.

func TimeOp

func TimeOp(r Rail, start time.Time, name string, args ...any)

Run timer for named operation and print result in log

e.g.,

defer TimeOp(rail, time.Now(), "someOperation")

func TraceMiddleware

func TraceMiddleware() gin.HandlerFunc

Tracing Middleware

func TraceRequest

func TraceRequest(ctx context.Context, req *http.Request) *http.Request

Wraper request with tracing key/value pairs on http headers

func TriggerJob added in v0.2.12

func TriggerJob(rail Rail, name string) error

Trigger Named Job.

func TriggerServerChangeListeners added in v0.1.12

func TriggerServerChangeListeners(service string)

Trigger service changes listeners.

func UnmarshalFromProp

func UnmarshalFromProp(ptr any)

Unmarshal configuration.

func UnmarshalFromPropAs added in v0.3.7

func UnmarshalFromPropAs[T any]() T

Unmarshal configuration.

func UnmarshalFromPropKey added in v0.0.22

func UnmarshalFromPropKey(key string, ptr any)

Unmarshal configuration from a speicific key.

func UnmarshalFromPropKeyAs added in v0.3.7

func UnmarshalFromPropKeyAs[T any](key string) T

Unmarshal configuration from a speicific key.

func Validate

func Validate(target any) error

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 ValidateIntRule(ival int64, rule string, fname string, param string) error

func ValidateRule

func ValidateRule(field reflect.StructField, value reflect.Value, rule string, ruleParam string) error

Types

type ApiDocFuzzType added in v0.4.10

type ApiDocFuzzType struct {
	PkgPath  string
	TypeName string
}

type AppConfig added in v0.1.12

type AppConfig struct {
	// contains filtered or unexported fields
}

func (*AppConfig) DefaultReadConfig added in v0.1.12

func (a *AppConfig) DefaultReadConfig(args []string)

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 (a *AppConfig) GetDefaultConfigFileLoaded() []string

func (*AppConfig) GetPropAny added in v0.1.30

func (a *AppConfig) GetPropAny(prop string) any

Get prop as any

func (*AppConfig) GetPropBool added in v0.1.12

func (a *AppConfig) GetPropBool(prop string) bool

Get prop as bool

func (*AppConfig) GetPropDur deprecated added in v0.1.12

func (a *AppConfig) GetPropDur(prop string, unit time.Duration) time.Duration

Get prop as time.Duration

Deprecated: Use GetPropDuration() instead.

func (*AppConfig) GetPropDuration added in v0.2.1

func (a *AppConfig) GetPropDuration(prop string) time.Duration

Get prop as time.Duration

func (*AppConfig) GetPropFloat added in v0.4.8

func (a *AppConfig) GetPropFloat(prop string) float64

Get prop as float64

func (*AppConfig) GetPropInt added in v0.1.12

func (a *AppConfig) GetPropInt(prop string) int

Get prop as int

func (*AppConfig) GetPropIntSlice added in v0.1.12

func (a *AppConfig) GetPropIntSlice(prop string) []int

Get prop as int slice

func (*AppConfig) GetPropStr added in v0.1.12

func (a *AppConfig) GetPropStr(prop string) string

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

func (a *AppConfig) GetPropStrMap(prop string) map[string]string

Get prop as string based map.

func (*AppConfig) GetPropStrSlice added in v0.1.12

func (a *AppConfig) GetPropStrSlice(prop string) []string

Get prop as string slice

func (*AppConfig) GetPropStrTrimmed added in v0.1.30

func (a *AppConfig) GetPropStrTrimmed(prop string) string

Same as GetPropStr() except the returned string is trimmed

func (*AppConfig) HasProp added in v0.1.12

func (a *AppConfig) HasProp(prop string) bool

Check whether the prop exists

func (*AppConfig) IsProdMode added in v0.1.12

func (a *AppConfig) IsProdMode() bool

Check whether we are running in production mode

func (*AppConfig) LoadConfigFromFile added in v0.1.12

func (a *AppConfig) LoadConfigFromFile(configFile string) error

Load config from file.

Calling this method overides previously loaded config.

func (*AppConfig) LoadConfigFromReader added in v0.1.12

func (a *AppConfig) LoadConfigFromReader(reader io.Reader) error

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

func (a *AppConfig) LoadConfigFromStr(s string) error

Load config from string.

Calling this method overides previously loaded config.

func (*AppConfig) OverwriteConf added in v0.1.12

func (a *AppConfig) OverwriteConf(args []string)

Overwrite existing conf using environment and cli args.

func (*AppConfig) ReloadConfigFromReader added in v0.1.28

func (a *AppConfig) ReloadConfigFromReader(reader io.Reader) error

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

func (a *AppConfig) ReloadConfigFromStr(sl ...string) error

Reload config from string.

Calling this method completely reloads previously loaded config.

func (*AppConfig) ResolveArg added in v0.1.12

func (a *AppConfig) ResolveArg(arg string) string

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

func (a *AppConfig) SetDefProp(prop string, defVal any)

Set default value for the prop

func (*AppConfig) SetProp added in v0.1.12

func (a *AppConfig) SetProp(prop string, val any)

Set value for the prop

func (*AppConfig) UnmarshalFromProp added in v0.1.12

func (a *AppConfig) UnmarshalFromProp(ptr any)

Unmarshal configuration.

func (*AppConfig) UnmarshalFromPropKey added in v0.1.12

func (a *AppConfig) UnmarshalFromPropKey(key string, ptr any)

Unmarshal configuration from a speicific key.

func (*AppConfig) WriteConfigAs added in v0.1.24

func (a *AppConfig) WriteConfigAs(filename string) (err error)

type CTFormatter

type CTFormatter = flow.CTFormatter

type Client added in v0.3.0

type Client 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 NewClient added in v0.3.0

func NewClient(rail Rail, url string) *Client

Create new miso HTTP Client.

func NewDynClient added in v0.3.0

func NewDynClient(rail Rail, relUrl string, serviceName string) *Client

Create new defualt Client with EnableServiceDiscovery(), EnableTracing(), and Require2xx() turned on.

The provided relUrl should be a relative url starting with '/'.

func (*Client) AddAuthBearer added in v0.3.0

func (t *Client) AddAuthBearer(v string) *Client

Add Authorization: Bearer *** header.

func (*Client) AddAuthHeader added in v0.3.0

func (t *Client) AddAuthHeader(v string) *Client

Add Authorization: *** header.

func (*Client) AddHeader added in v0.3.0

func (t *Client) AddHeader(k string, v string) *Client

Append header, subsequent method calls doesn't override previously appended headers

func (*Client) AddHeaders added in v0.3.0

func (t *Client) AddHeaders(headers map[string]string) *Client

Append headers, subsequent method calls doesn't override previously appended headers

func (*Client) AddQuery added in v0.4.10

func (t *Client) AddQuery(k string, v ...any) *Client

Append Query Parameters, subsequent method calls doesn't override previously appended parameters

func (*Client) AddQueryParams deprecated added in v0.3.0

func (t *Client) AddQueryParams(k string, v ...any) *Client

Deprecated: Since v0.4.10, use Client.AddQuery instead.

func (*Client) Connect added in v0.3.0

func (t *Client) Connect() *TResponse

func (*Client) Delete added in v0.3.0

func (t *Client) Delete() *TResponse

Send DELETE request

func (*Client) EnableServiceDiscovery added in v0.3.0

func (t *Client) EnableServiceDiscovery(serviceName string) *Client

Enable service discovery

func (*Client) EnableTracing added in v0.3.0

func (t *Client) EnableTracing() *Client

Enable tracing by putting propagation key/value pairs on http headers.

func (*Client) Get added in v0.3.0

func (t *Client) Get() *TResponse

Send GET request

func (*Client) Head added in v0.3.0

func (t *Client) Head() *TResponse

Send HEAD request

func (*Client) Http added in v0.3.0

func (t *Client) Http() *Client

Append 'http://' protocol.

If service discovery is enabled, or the url contains http protocol already, this will be skipped.

func (*Client) Https added in v0.3.0

func (t *Client) Https() *Client

Append 'https://' protocol.

If service discovery is enabled, or the url contains http protocol already, this will be skipped.

func (*Client) LogBody added in v0.3.0

func (t *Client) LogBody() *Client

func (*Client) Options added in v0.3.0

func (t *Client) Options() *TResponse

Send OPTIONS request

func (*Client) Patch added in v0.3.0

func (t *Client) Patch() *TResponse

func (*Client) Post added in v0.3.0

func (t *Client) Post(body io.Reader) *TResponse

Send POST request with reader to request body.

func (*Client) PostBytes added in v0.3.0

func (t *Client) PostBytes(body []byte) *TResponse

Send POST request with bytes.

func (*Client) PostForm added in v0.3.0

func (t *Client) PostForm(data url.Values) *TResponse

Send POST request with urlencoded form data

func (*Client) PostFormData added in v0.3.0

func (t *Client) PostFormData(data map[string]io.Reader) *TResponse

Send POST request with urlencoded form data

Caller is responsible for closing all the reader.

func (*Client) PostJson added in v0.3.0

func (t *Client) PostJson(body any) *TResponse

Send POST request with JSON.

Use simple types like struct instad of pointer for body.

func (*Client) Put added in v0.3.0

func (t *Client) Put(body io.Reader) *TResponse

Send PUT request

func (*Client) PutBytes added in v0.3.0

func (t *Client) PutBytes(body []byte) *TResponse

Send PUT request with bytes.

func (*Client) PutForm added in v0.3.0

func (t *Client) PutForm(data url.Values) *TResponse

Send PUT request with urlencoded form data

func (*Client) PutFormData added in v0.3.0

func (t *Client) PutFormData(data map[string]io.Reader) *TResponse

Send PUT request with urlencoded form data

Caller is responsible for closing all the reader.

func (*Client) PutJson added in v0.3.0

func (t *Client) PutJson(body any) *TResponse

Send PUT request with JSON

func (*Client) Require2xx added in v0.3.0

func (t *Client) Require2xx() *Client

Requires response to have 2xx status code, if not, the *TResponse will contain error built for this specific reason.

func (*Client) SetContentType added in v0.3.0

func (t *Client) SetContentType(ct string) *Client

Set Content-Type

func (*Client) SetHeaders added in v0.3.0

func (t *Client) SetHeaders(k string, v ...string) *Client

Overwrite header

func (*Client) Trace added in v0.3.0

func (t *Client) Trace() *TResponse

func (*Client) UseClient added in v0.3.0

func (t *Client) UseClient(client *http.Client) *Client

Change the underlying *http.Client

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

type ConsulServerList struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

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

type CpuStats struct {
	Goroutines int
	CpuUsage   float64
}

func CollectCpuStats added in v0.1.27

func CollectCpuStats() (CpuStats, error)

type DynAuthRoute added in v0.4.11

type DynAuthRoute struct {
	Name         string
	Type         string // Bearer / Basic
	Bearer       string
	Username     string
	Password     string
	PathPatterns []string
	// contains filtered or unexported fields
}

func (*DynAuthRoute) BuildBasic added in v0.4.11

func (d *DynAuthRoute) BuildBasic() string

func (*DynAuthRoute) CheckAuth added in v0.4.11

func (d *DynAuthRoute) CheckAuth(v *dynAuthReq) bool

type FieldDesc added in v0.1.11

type FieldDesc struct {
	GoFieldName           string // field name in golang
	JsonName              string // field name in json
	TypeNameAlias         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
	DescTag               string // `desc` tag value
	JsonTag               string // `json` tag value
	ValidTag              string // `validate` tag value

	Fields []FieldDesc // struct fields
	// contains filtered or unexported fields
}

func (FieldDesc) TypeInfo added in v0.4.10

func (f FieldDesc) TypeInfo() (pkg string, name string)

type GatewayError added in v0.3.5

type GatewayError struct {
	StatusCode int
}

func (GatewayError) Error added in v0.3.5

func (g GatewayError) Error() string

func (GatewayError) Status added in v0.3.5

func (g GatewayError) Status() int

type GetPipelineDocFunc added in v0.1.0

type GetPipelineDocFunc func() []PipelineDoc

type GinPreProcessor added in v0.0.16

type GinPreProcessor func(rail Rail, engine *gin.Engine)

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

func OkGnResp added in v0.0.25

func OkGnResp[T any](data T) GnResp[T]

func WrapGnResp added in v0.0.25

func WrapGnResp[T any](data T, err error) (GnResp[T], error)

func (GnResp[T]) CheckErr added in v0.4.10

func (r GnResp[T]) CheckErr() error

func (GnResp[T]) Err

func (r GnResp[T]) Err() error

func (GnResp[T]) MappedRes added in v0.0.15

func (r GnResp[T]) MappedRes(mapper map[string]error) (T, error)

func (GnResp[T]) Res added in v0.0.3

func (r GnResp[T]) Res() (T, error)

func (GnResp[T]) Unwrap added in v0.0.25

func (r GnResp[T]) Unwrap() 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 HealthStatus struct {
	Name    string
	Healthy bool
}

func CheckHealth added in v0.0.6

func CheckHealth(rail Rail) []HealthStatus

Check health status.

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

func (t *HistTimer) ObserveDuration() time.Duration

func (*HistTimer) Reset added in v0.0.25

func (t *HistTimer) Reset()

type HttpError added in v0.2.0

type HttpError struct {
	StatusCode int
	Body       string
}

func (HttpError) Error added in v0.2.0

func (he HttpError) Error() string

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 1min, MaxIdleConns is 0, 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
})

See NewDynProxyTargetResolver.

func (*HttpProxy) AddAccessFilter added in v0.3.8

func (h *HttpProxy) AddAccessFilter(whitelistPatterns func() []string, checkAuth func(pc *ProxyContext) (statusCode int, ok bool))

Add Access Filter.

See [HttpProxy.WithBearerAuthCheck].

func (*HttpProxy) AddDebugFilter added in v0.3.8

func (h *HttpProxy) AddDebugFilter(mustAuthInProd bool) error

Add Filter for /debug/pprof/** and /debug/trace/** paths.

Only active when the proxied path is '/'.

func (*HttpProxy) AddFilter added in v0.1.10

func (h *HttpProxy) AddFilter(f ProxyFilter)

func (*HttpProxy) AddHealthcheckFilter added in v0.3.8

func (h *HttpProxy) AddHealthcheckFilter()

Add Filter for healthcheck.

Only active when the proxied path is '/'.

func (*HttpProxy) AddIPBlacklistFilter added in v0.4.10

func (h *HttpProxy) AddIPBlacklistFilter(matchBlacklist func(ip string) bool)

func (*HttpProxy) AddMetricsFilter added in v0.3.8

func (h *HttpProxy) AddMetricsFilter(hiso prometheus.Histogram, exclPath func(proxyPath string) bool)

Add Filter for metrics and prometheus.

Only active when the proxied path is '/'.

func (*HttpProxy) AddPathFilter added in v0.3.8

func (h *HttpProxy) AddPathFilter(pathPatterns []string, f ProxyFilter)

func (*HttpProxy) AddReqTimeLogFilter added in v0.3.8

func (h *HttpProxy) AddReqTimeLogFilter(exclPath func(proxyPath string) bool, unit ...ReqTimeLogUnit)

func (*HttpProxy) ChangeClient added in v0.1.13

func (h *HttpProxy) ChangeClient(c *http.Client)

func (*HttpProxy) JoinCheckAuth added in v0.4.11

func (h *HttpProxy) JoinCheckAuth(checkAuth ...func(pc *ProxyContext) (statusCode int, ok bool)) func(pc *ProxyContext) (statusCode int, ok bool)

func (*HttpProxy) LoadDynAuthRouteFromProp added in v0.4.11

func (h *HttpProxy) LoadDynAuthRouteFromProp(rootProp string) []DynAuthRoute

Load DynAuthRoute from configuration.

E.g.,

root-prop:
  - name: "myauth1"
    type: "bearer"
    bearer: "mybearer1"
    path-patterns:
      - "/path1"
      - "/path2"
      - "/path3"
  - name: "myauth2"
    type: "basic"
    username: "myuser"
    password: "mypassword"
    path-patterns:
      - "/path4"
      - "/path5"
      - "/path6"

func (*HttpProxy) WithDynAuthCheck added in v0.4.11

func (h *HttpProxy) WithDynAuthCheck(load func() []DynAuthRoute) func(pc *ProxyContext) (statusCode int, ok bool)

Check Authorization With dynamically loaded DynAuthRoute.

E.g.,

var h *miso.HttpProxy
h.WithDynAuthCheck(func() []DynAuthRoute{
	return h.LoadDynAuthRouteFromProp("root-prop")
})

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).
}

func GetHttpRoutes

func GetHttpRoutes() []HttpRoute

Get recorded http server routes

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 that directly/indirectly calls miso's methods.

func (*Inbound) AddHeader added in v0.0.26

func (i *Inbound) AddHeader(k string, v string)

func (*Inbound) Engine added in v0.0.26

func (i *Inbound) Engine() any

func (*Inbound) HandleResult added in v0.0.26

func (i *Inbound) HandleResult(result any, err error)

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) Header added in v0.0.26

func (i *Inbound) Header(k string) string

func (*Inbound) Headers added in v0.2.8

func (i *Inbound) Headers() http.Header

func (*Inbound) LogHeaders added in v0.4.11

func (i *Inbound) LogHeaders()

func (*Inbound) LogRequest added in v0.3.2

func (i *Inbound) LogRequest()

func (*Inbound) MustBind added in v0.1.21

func (i *Inbound) MustBind(ptr any)

func (*Inbound) Queries added in v0.2.8

func (i *Inbound) Queries() url.Values

func (*Inbound) Query added in v0.0.26

func (i *Inbound) Query(k string) string

func (*Inbound) Rail added in v0.0.26

func (i *Inbound) Rail() Rail

func (*Inbound) ReadRawBytes added in v0.3.3

func (i *Inbound) ReadRawBytes() ([]byte, error)

func (*Inbound) Request added in v0.2.11

func (i *Inbound) Request() *http.Request

func (*Inbound) SetHeader added in v0.0.26

func (i *Inbound) SetHeader(k string, v string)

func (*Inbound) Status added in v0.0.26

func (i *Inbound) Status(status int)

func (*Inbound) Unwrap added in v0.0.26

func (i *Inbound) Unwrap() (http.ResponseWriter, *http.Request)

func (*Inbound) WriteJson added in v0.1.21

func (i *Inbound) WriteJson(v any)

func (*Inbound) WriteJsonStatus added in v0.1.21

func (i *Inbound) WriteJsonStatus(v any, httpStatus int)

func (*Inbound) WriteSSE added in v0.2.11

func (i *Inbound) WriteSSE(name string, message any)

func (*Inbound) WriteString added in v0.2.0

func (i *Inbound) WriteString(v string)

func (*Inbound) Writer added in v0.2.11

func (i *Inbound) Writer() http.ResponseWriter

type Job added in v0.0.8

type Job struct {
	Name                   string                // name of the job.
	Cron                   string                // cron expr.
	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
	LogErrWarnLevel        bool                  // print WARN level log when job failed, by default log is printed in ERROR level.
	// contains filtered or unexported fields
}

type JobExecStats added in v0.0.8

type JobExecStats struct {
	Time time.Duration
	Err  error
}

type JobInf added in v0.0.8

type JobInf struct {
	Name            string
	Cron            string
	CronWithSeconds bool
}

type JsonPayloadDesc added in v0.1.9

type JsonPayloadDesc = TypeDesc

type LazyRouteDecl added in v0.0.23

type LazyRouteDecl struct {
	Url     string
	Method  string
	Handler func(c *gin.Context)

	RegisterFunc func(extra ...pair.Pair[string, any])
	Extras       []pair.Pair[string, any]
}

Lazy route declaration

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 (*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

type LocalCache[T any] map[string]T

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.

Migrate to NewLocalCacheV2 if possible.

func (LocalCache[T]) Get

func (lc LocalCache[T]) Get(key string, supplier func(string) (T, error)) (T, error)

Get cached value identified by the key, if absent, call the supplier func instead, and cache and return the supplied value.

type LocalCacheV2 added in v0.2.5

type LocalCacheV2[K comparable, T any] map[K]T

Simple local map-based cache.

This should not be a long-live object.

func NewLocalCacheV2 added in v0.2.5

func NewLocalCacheV2[K comparable, T any]() LocalCacheV2[K, T]

Create new LocalCache with key of type K and value of type T.

func (LocalCacheV2[K, T]) Get added in v0.2.5

func (lc LocalCacheV2[K, T]) Get(key K, supplier func() (T, error)) (T, error)

Get cached value identified by the key, if absent, call the supplier func instead, and cache and return the supplied value.

func (LocalCacheV2[K, T]) Set added in v0.2.5

func (lc LocalCacheV2[K, T]) Set(key K, t T)

func (LocalCacheV2[K, T]) ToMap added in v0.2.5

func (lc LocalCacheV2[K, T]) ToMap() map[K]T

func (LocalCacheV2[K, T]) TryGet added in v0.2.6

func (lc LocalCacheV2[K, T]) TryGet(key K) (T, bool)

Get cached value identified by the key

type MappedTRouteHandler

type MappedTRouteHandler[Req any, Res any] func(inb *Inbound, req Req) (Res, error)

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 (a *MisoApp) AddOrderedAsyncShutdownHook(order int, hook func())

func (*MisoApp) AddOrderedShutdownHook added in v0.1.12

func (a *MisoApp) AddOrderedShutdownHook(order int, hook func())

func (*MisoApp) AddShutdownHook added in v0.1.12

func (a *MisoApp) AddShutdownHook(hook func())

func (*MisoApp) Bootstrap added in v0.1.12

func (a *MisoApp) Bootstrap(args []string)

Bootstrap miso app.

func (*MisoApp) Config added in v0.1.12

func (a *MisoApp) Config() *AppConfig

func (*MisoApp) IsShuttingDown added in v0.1.12

func (a *MisoApp) IsShuttingDown() bool

check if the server is shutting down

func (*MisoApp) LoadConfig added in v0.1.12

func (a *MisoApp) LoadConfig(args []string)

Load app configuration.

func (*MisoApp) OnAppReady added in v0.2.1

func (a *MisoApp) OnAppReady(callback ...func(rail Rail) error)

func (*MisoApp) PostServerBootstrap added in v0.1.12

func (a *MisoApp) PostServerBootstrap(callback ...func(rail Rail) error)

func (*MisoApp) PreServerBootstrap added in v0.1.12

func (a *MisoApp) PreServerBootstrap(callback ...func(rail Rail) error)

func (*MisoApp) RegisterBootstrapCallback added in v0.1.12

func (a *MisoApp) RegisterBootstrapCallback(bootstrapComponent ComponentBootstrap)

func (*MisoApp) RegisterConfigLoader added in v0.2.0

func (a *MisoApp) RegisterConfigLoader(callback ...func(rail Rail) error)

func (*MisoApp) Shutdown added in v0.1.12

func (a *MisoApp) Shutdown()

Shutdown server

func (*MisoApp) Store added in v0.1.12

func (a *MisoApp) Store() *appStore

type MisoErr added in v0.0.3

type MisoErr = errs.MisoErr

type NewRollingLogFileParam

type NewRollingLogFileParam = flow.NewRollingLogFileParam

type OrderedShutdownHook added in v0.0.23

type OrderedShutdownHook struct {
	Hook  func() async.Future[any]
	Order int
}

type PageReq added in v0.3.1

type PageReq struct {
	Paging Paging `json:"paging" desc:"pagination parameters"`
}

type PageRes

type PageRes[T any] struct {
	Page    Paging `json:"paging" desc:"pagination parameters"`
	Payload []T    `json:"payload" desc:"payload values in current page"`
}

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 RespPage

func RespPage(reqPage Paging, total int) Paging

Build Paging for response

func (Paging) GetLimit

func (p Paging) GetLimit() int

func (Paging) GetOffset

func (p Paging) GetOffset() int

func (Paging) GetPage

func (p Paging) GetPage() int

func (*Paging) NextPage added in v0.1.15

func (p *Paging) NextPage()

func (Paging) ToRespPage

func (p Paging) ToRespPage(total int) Paging

type ParamDoc added in v0.0.22

type ParamDoc struct {
	Name string
	Desc string
}

type PipelineDoc added in v0.0.33

type PipelineDoc struct {
	Name        string
	Desc        string
	Exchange    string
	RoutingKey  string
	Queue       string
	PayloadDesc TypeDesc
}

type PlainStrFormatter added in v0.1.13

type PlainStrFormatter = flow.PlainStrFormatter

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

type PreJobHook func(rail Rail, inf JobInf) error

Hook triggered before job's execution.

type PropagationKeys

type PropagationKeys = flow.PropagationKeys

type ProxyContext added in v0.1.10

type ProxyContext struct {
	Rail      *Rail
	Inb       *Inbound
	ProxyPath string // Proxied path without query parameters.
	// 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

type ProxyTargetResolver func(rail Rail, proxyPath string) (string, error)

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.

func NewDynProxyTargetResolver added in v0.3.5

func NewDynProxyTargetResolver() ProxyTargetResolver

Resolve proxy target based on service discovery.

type Rail

type Rail = flow.Rail

func BuildRail

func BuildRail(c *gin.Context) Rail

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 LoadPropagationKeysFromHeaders added in v0.2.8

func LoadPropagationKeysFromHeaders[T any](rail Rail, headers map[string]T) Rail

func PrepareTestEnv added in v0.2.2

func PrepareTestEnv(t *testing.T) Rail

Prepare Test Environment

Before calling this method, you should make sure related modules are imported in go test file, or else the dependencies may not be bootstrapped properly.

type RawTRouteHandler

type RawTRouteHandler func(inb *Inbound)

Raw version of traced route handler.

type ReqTimeLogUnit added in v0.4.9

type ReqTimeLogUnit struct {
	Dur  time.Duration
	Name string
}

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

func ErrorResp

func ErrorResp(msg string) Resp

Build error Resp

func ErrorRespWCode

func ErrorRespWCode(code string, msg string) Resp

Build error Resp

func OkResp

func OkResp() Resp

Build OK Resp

func OkRespWData

func OkRespWData(data interface{}) Resp

Build OK Resp with data

func WrapResp

func WrapResp(rail Rail, data interface{}, err error, url string) Resp

Wrap result (data and err) with a common Resp object.

If err is not nil, returns a Resp body containing the error code and message. If err is nil, the data is wrapped inside a Resp object and returned with http.StatusOK.

func (Resp) CheckErr added in v0.4.10

func (r Resp) CheckErr() error

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

type RoutingGroup struct {
	Base  string
	Paths []TreePath
}

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

type Server struct {
	Protocol string
	Address  string
	Port     int
	Meta     map[string]string
}

func SelectAnyServer added in v0.0.22

func SelectAnyServer(rail Rail, name string) (Server, error)

Select one Server randomly.

func SelectServer added in v0.0.14

func SelectServer(rail Rail, name string, selector func(servers []Server) int) (Server, error)

Select one Server based on the provided selector algorithm.

func (*Server) BuildUrl added in v0.0.14

func (c *Server) BuildUrl(relUrl string) string

Build the complete request url.

func (*Server) ServerAddress added in v0.0.14

func (c *Server) ServerAddress() string

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      async.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

func (c ServerListServiceRegistry) ResolveUrl(rail Rail, service string, relativeUrl string) (string, error)

type ServerSelector added in v0.0.14

type ServerSelector func(servers []Server) int

Server selector, returns index of the selected one.

type ServicePath added in v0.3.5

type ServicePath struct {
	ServiceName string
	Path        string
}

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

func NewTBucket[T any](val T) TBucket[T]

type TClient

type TClient = Client

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

func (tr *TResponse) Bytes() ([]byte, error)

Read response as []bytes.

Response is always closed automatically.

If response body is somehow empty, *miso.NoneErr is returned.

func (*TResponse) Close

func (tr *TResponse) Close() error

Close Response

func (*TResponse) Is2xx

func (tr *TResponse) Is2xx() bool

Is status code 2xx

func (*TResponse) Json added in v0.0.3

func (tr *TResponse) Json(ptr any) error

Read response as JSON object.

Response is always closed automatically.

If response body is somehow empty, *miso.NoneErr is returned.

If ptr impl TResponseJsonCheckErr, [TResponseJsonCheckErr.CheckErr] is called after json unmarshalling.

func (*TResponse) JsonStr added in v0.4.10

func (tr *TResponse) JsonStr(ptr any) (_originalJson string, _err error)

Read response as JSON object.

Response is always closed automatically.

If response body is somehow empty, *miso.NoneErr is returned.

If ptr impl TResponseJsonCheckErr, [TResponseJsonCheckErr.CheckErr] is called after json unmarshalling.

func (*TResponse) Ok added in v0.3.2

func (tr *TResponse) Ok() error

Check if response ok.

Response is always closed automatically.

func (*TResponse) Require2xx

func (tr *TResponse) Require2xx() error

Check if it's 2xx, else return error

func (*TResponse) Sse added in v0.1.17

func (tr *TResponse) Sse(parse func(e sse.Event) (stop bool, err error), options ...func(c *SseReadConfig)) error

func (*TResponse) Str added in v0.0.3

func (tr *TResponse) Str() (string, error)

Read response as string.

Response is always closed automatically.

If response body is somehow empty, *miso.NoneErr is returned.

func (*TResponse) WriteTo added in v0.0.15

func (tr *TResponse) WriteTo(writer io.Writer) (int64, error)

Write the response data to the given writer.

Response is always closed automatically.

If response body is somehow empty, *miso.NoneErr is returned.

func (*TResponse) WriteToFile added in v0.2.6

func (tr *TResponse) WriteToFile(path string) (int64, error)

Write the response data to the file.

Response is always closed automatically.

If response body is somehow empty, *miso.NoneErr is returned.

type TResponseJsonCheckErr added in v0.1.19

type TResponseJsonCheckErr interface {
	CheckErr() error
}

type TRouteHandler

type TRouteHandler[Res any] func(inb *Inbound) (Res, error)

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

func NewTTLCache[T any](ttl time.Duration, maxSize int) TTLCache[T]

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 = async.TickRunner

type TreePath added in v0.0.23

type TreePath interface {
	Prepend(baseUrl string)
}

type TypeDesc added in v0.4.10

type TypeDesc struct {
	TypeName   string
	TypePkg    string
	IsPtr      bool
	IsPtrSlice bool
	IsSlice    bool
	IsSlicePtr bool
	Fields     []FieldDesc
}

See BuildTypeDesc

func BuildTypeDesc added in v0.4.10

func BuildTypeDesc(v reflect.Value) TypeDesc

Parse value's type information to build json style description.

Only supports struct, pointer and slice.

func (TypeDesc) TypeInfo added in v0.4.10

func (f TypeDesc) TypeInfo() (pkg string, name string)

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.

func (*VecTimer) ObserveDuration added in v0.0.13

func (t *VecTimer) ObserveDuration(labels ...string) time.Duration

func (*VecTimer) Reset added in v0.0.25

func (t *VecTimer) Reset()

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL