Documentation
¶
Overview ¶
Qore Go toolkit.
Index ¶
- Constants
- Variables
- func ContextFromHttp(c HttpContext) (ctx context.Context)
- func ContextGetTraceID(ctx context.Context) string
- func HttpHanlderChain(h HttpHandlerable) *httpHandlerChainImpl[HttpRequestPayload]
- func HttpHanlderChainWithPayload[T HttpRequestPayload](h HttpHandlerableWithPayload[T]) *httpHandlerChainImpl[T]
- func SliceRemoveItems[T comparable](src, target []T) []T
- func StringAlphaNumRandom(length uint8) (string, error)
- func StringIsFirstCharNonAlphabet(s string) bool
- func StringRemoveNonAlphabet(s string) string
- func StringToCammelCase(s string) string
- func StringToSnakeCase(s string) string
- func ValidationIsEmpty[T Validatable](s T) bool
- type ApiResponse
- type ApiResponseDefault
- type ApiResponseInterface
- type App
- func (app *App) LoadModule(loader ModuleLoader)
- func (a *App) Logger() *logger
- func (app *App) SetApiResponseInterface(iApiResponse ApiResponseInterface)
- func (app *App) SetHttpMiddleware(middlewares ...HttpMiddleware)
- func (app *App) SetHttpRoutes(fn func(router *HttpRouter))
- func (app *App) SetHttpValidator(validator HttpValidator)
- func (app *App) Start(supervisor ...Supervisor)
- type Config
- type Dependency
- type DependencyStats
- type HttpContext
- type HttpHandler
- type HttpHandlerChain
- type HttpHandlerable
- type HttpHandlerableWithPayload
- type HttpMiddleware
- type HttpRequestPayload
- type HttpResponseClientError
- type HttpResponseRedirect
- type HttpResponseServerError
- type HttpResponseSuccess
- type HttpRouter
- func (r *HttpRouter) Connect(path string, handler HttpHandlerChain[HttpRequestPayload], ...)
- func (r *HttpRouter) Delete(path string, handler HttpHandlerChain[HttpRequestPayload], ...)
- func (r *HttpRouter) Get(path string, handler HttpHandlerChain[HttpRequestPayload], ...)
- func (r *HttpRouter) Group(prefix string, fn func(group *HttpRouter), middlewares ...HttpMiddleware)
- func (r *HttpRouter) Head(path string, handler HttpHandlerChain[HttpRequestPayload], ...)
- func (r *HttpRouter) Options(path string, handler HttpHandlerChain[HttpRequestPayload], ...)
- func (r *HttpRouter) Patch(path string, handler HttpHandlerChain[HttpRequestPayload], ...)
- func (r *HttpRouter) Post(path string, handler HttpHandlerChain[HttpRequestPayload], ...)
- func (r *HttpRouter) Put(path string, handler HttpHandlerChain[HttpRequestPayload], ...)
- func (r *HttpRouter) Trace(path string, handler HttpHandlerChain[HttpRequestPayload], ...)
- type HttpValidator
- type HttpValidatorErr
- type LogLevel
- type Module
- type ModuleLoader
- type Numeric
- type Responder
- type Supervisor
- type SupervisorGraceful
- type SupervisorNon
- type Validatable
Constants ¶
const ( // HTTP header key for trace id. HTTP_HEADER_TRACE_ID = "X-Trace-ID" // HTTP context key for trace id HTTP_CONTEXT_TRACE_ID = "traceId" // HTTP context key for auth session. HTTP_CONTEXT_AUTH = "auth" )
const CONFIG_USED_KEY = "USED_CONFIG"
Config used key.
const (
// Context key for Trace ID.
CTX_TRACE_ID = contextKey("traceId")
)
Variables ¶
var (
ErrHttpValidatorNotRegistered = errors.New("validator not registered")
)
Functions ¶
func ContextFromHttp ¶
func ContextFromHttp(c HttpContext) (ctx context.Context)
ContextFromHttp wraps HTTP(s) request context and return `context.Context`.
func ContextGetTraceID ¶
ContextGetTraceID returns value of Trace ID from context.
func HttpHanlderChain ¶
func HttpHanlderChain(h HttpHandlerable) *httpHandlerChainImpl[HttpRequestPayload]
HttpHanlderChain returns `HttpHandlerChain` that wrap user's handler.
func HttpHanlderChainWithPayload ¶
func HttpHanlderChainWithPayload[T HttpRequestPayload](h HttpHandlerableWithPayload[T]) *httpHandlerChainImpl[T]
HttpHanlderChainWithPayload returns `HttpHandlerChain` that wrap user's handler using given payload type.
func SliceRemoveItems ¶
func SliceRemoveItems[T comparable](src, target []T) []T
SliceRemoveItems removes item(s) in `src` that have in `target`.
func StringAlphaNumRandom ¶
StringAlphaNumRandom generate alpha numeric random string. It will return random string and an error if failed to read the bytes.
func StringIsFirstCharNonAlphabet ¶
StringIsFirstCharNonAlphabet checks is first character from given string contains non-alphabet.
func StringRemoveNonAlphabet ¶
StringRemoveNonAlphabet removes non-alphabet characters from given string.
func StringToCammelCase ¶
StringToCammelCase converts given string to the cammel case.
func StringToSnakeCase ¶
StringToSnakeCase converts given string to the snake case.
func ValidationIsEmpty ¶
func ValidationIsEmpty[T Validatable](s T) bool
ValidationIsEmpty will checks is value of argument s was empty.
Types ¶
type ApiResponse ¶
type ApiResponse interface {
// Success returns `ApiResponse` with HTTP(s) success status (2xx).
Success(status HttpResponseSuccess, data ...any) ApiResponse
// Error returns `ApiResponse` but should be check the error,
// so it may return client or server error based on given error.
Error(err error) ApiResponse
// ClientError returns `ApiResponse` with HTTP(s) client error status (4xx).
ClientError(status HttpResponseClientError, err error) ApiResponse
// ServerError returns `ApiResponse` with HTTP(s) server error status (5xx).
ServerError(status HttpResponseServerError, err error) ApiResponse
// WithMessage returns `ApiResponse` with response message.
WithMessage(msg string) ApiResponse
// WithMessage returns `ApiResponse` with response code.
WithCode(code any) ApiResponse
// WithMessage returns `ApiResponse` with additional data in the response.
WithAdditional(data any) ApiResponse
// Response write the `ApiResponse`. Returning error or nil.
Response() error
}
ApiResponse defines the response wrapper interface for HTTP(s) API.
type ApiResponseDefault ¶
type ApiResponseDefault struct {
Success bool `json:"success" xml:"success"`
Code string `json:"code" xml:"code"`
Data any `json:"data" xml:"data"`
Error any `json:"error" xml:"error"`
}
ApiResponseDefault defines default API response object.
type ApiResponseInterface ¶
type ApiResponseInterface interface {
New(c HttpContext) ApiResponse
}
ApiResponseInterface defines the `HttpResponder` interface to creating the instance.
type App ¶
type App struct {
// Config value that parsed from env or file, can be used by application.
Config *Config
// contains filtered or unexported fields
}
App is the Qore main application.
func (*App) LoadModule ¶
func (app *App) LoadModule(loader ModuleLoader)
LoadModule will loaded all used module(s).
func (*App) SetApiResponseInterface ¶
func (app *App) SetApiResponseInterface(iApiResponse ApiResponseInterface)
SetApiResponseInterface will set custom HTTP(s) API response wrapper.
func (*App) SetHttpMiddleware ¶
func (app *App) SetHttpMiddleware(middlewares ...HttpMiddleware)
SetHttpMiddleware will set given middleware(s) to the global HTTP(S) middleware.
func (*App) SetHttpRoutes ¶
func (app *App) SetHttpRoutes(fn func(router *HttpRouter))
SetHttpRoutes creates HTTP routers object that can be used for registering HTTP route.
func (*App) SetHttpValidator ¶
func (app *App) SetHttpValidator(validator HttpValidator)
SetHttpValidator will set custom request validator to the HTTP(S).
func (*App) Start ¶
func (app *App) Start(supervisor ...Supervisor)
Start will starting the application services with optional supervisor argument. Supervisor is process manager that handle application graceful lifecycle. You can create supervisor by yourself using that implement Supervisor interface.
Using default supervisor (SupervisorNon)
app.Start()
Using gracefully stop & restart supervisor (SupervisorGraceful) backed by overseer https://github.com/jpillora/overseer
app.Start(&qore.SupervisorGraceful{
Signals: []os.Signal{
syscall.SIGUSR2,
syscall.SIGHUP,
syscall.SIGTSTP,
syscall.SIGINT,
os.Interrupt,
},
BinaryFilePath: "./tmp/main",
})
type Config ¶
type Config struct {
// App config.
AppName string `json:"APP_NAME" mapstructure:"APP_NAME"`
AppProduction bool `json:"APP_PRODUCTION" mapstructure:"APP_PRODUCTION"`
AppContainerized bool `json:"APP_CONTAINERIZED" mapstructure:"APP_CONTAINERIZED"`
ShutdownTimeout int `json:"APP_SHUTDOWN_TIMEOUT" mapstructure:"APP_SHUTDOWN_TIMEOUT"`
// Log config.
LogLevel LogLevel `json:"LOG_LEVEL" mapstructure:"LOG_LEVEL"`
LogJSON bool `json:"LOG_JSON" mapstructure:"LOG_JSON"`
LogShowSource bool `json:"LOG_SHOW_SOURCE" mapstructure:"LOG_SHOW_SOURCE"`
// HTTP Server config.
HTTPPort int `json:"HTTP_PORT" mapstructure:"HTTP_PORT"`
HTTPAutoTLS bool `json:"HTTP_AUTO_TLS" mapstructure:"HTTP_AUTO_TLS"`
HTTPCertPath string `json:"HTTP_CERT_PATH" mapstructure:"HTTP_CERT_PATH"`
HTTPKeyPath string `json:"HTTP_KEY_PATH" mapstructure:"HTTP_KEY_PATH"`
}
type Dependency ¶
type Dependency interface {
Name() string
Priority() int
HealthCheck(ctx context.Context) *DependencyStats
Open() error
Close() error
}
Dependency is package dependency interface.
type DependencyStats ¶ added in v0.2.2098
type DependencyStats struct {
UptimeSeconds float64 `json:"uptimeSeconds" xml:"uptimeSeconds"`
UptimeHuman string `json:"uptimeHuman" xml:"uptimeHuman"`
PINGResponse any `json:"pingResponse" xml:"pingResponse"`
PINGLatencyMillis int64 `json:"pingLatencyMillis" xml:"pingLatencyMillis"`
PINGLatencyHuman string `json:"pingLatencyHuman" xml:"pingLatencyHuman"`
Additional any `json:"additional" xml:"additional"`
}
DependencyStats defines dependency statistical health.
type HttpContext ¶
type HttpContext interface {
// Request returns `*http.Request`.
Request() *http.Request
// SetRequest sets `*http.Request`.
SetRequest(r *http.Request)
// SetResponse sets `*Response`.
SetResponse(r *echo.Response)
// Response returns `*Response`.
Response() *echo.Response
// IsTLS returns true if HTTP connection is TLS otherwise false.
IsTLS() bool
// IsWebSocket returns true if HTTP connection is WebSocket otherwise false.
IsWebSocket() bool
// Scheme returns the HTTP protocol scheme, `http` or `https`.
Scheme() string
// RealIP returns the client's network address based on `X-Forwarded-For`
// or `X-Real-IP` request header.
// The behavior can be configured using `Echo#IPExtractor`.
RealIP() string
// Path returns the registered path for the handler.
Path() string
// SetPath sets the registered path for the handler.
SetPath(p string)
// Param returns path parameter by name.
Param(name string) string
// ParamNames returns path parameter names.
ParamNames() []string
// SetParamNames sets path parameter names.
SetParamNames(names ...string)
// ParamValues returns path parameter values.
ParamValues() []string
// SetParamValues sets path parameter values.
SetParamValues(values ...string)
// QueryParam returns the query param for the provided name.
QueryParam(name string) string
// QueryParams returns the query parameters as `url.Values`.
QueryParams() url.Values
// QueryString returns the URL query string.
QueryString() string
// FormValue returns the form field value for the provided name.
FormValue(name string) string
// FormParams returns the form parameters as `url.Values`.
FormParams() (url.Values, error)
// FormFile returns the multipart form file for the provided name.
FormFile(name string) (*multipart.FileHeader, error)
// MultipartForm returns the multipart form.
MultipartForm() (*multipart.Form, error)
// Cookie returns the named cookie provided in the request.
Cookie(name string) (*http.Cookie, error)
// SetCookie adds a `Set-Cookie` header in HTTP response.
SetCookie(cookie *http.Cookie)
// Cookies returns the HTTP cookies sent with the request.
Cookies() []*http.Cookie
// Get retrieves data from the context.
Get(key string) any
// Set saves data in the context.
Set(key string, val any)
// Bind binds path params, query params and the request body into provided type `i`. The default binder
// binds body based on Content-Type header.
Bind(i any) error
// Validate validates provided `i`. It is usually called after `Context#Bind()`.
// Validator must be registered using `Echo#Validator`.
Validate(i any) error
// Render renders a template with data and sends a text/html response with status
// code. Renderer must be registered using `Echo.Renderer`.
Render(code int, name string, data any) error
// HTML sends an HTTP response with status code.
HTML(code int, html string) error
// HTMLBlob sends an HTTP blob response with status code.
HTMLBlob(code int, b []byte) error
// String sends a string response with status code.
String(code int, s string) error
// JSON sends a JSON response with status code.
JSON(code int, i any) error
// JSONPretty sends a pretty-print JSON with status code.
JSONPretty(code int, i any, indent string) error
// JSONBlob sends a JSON blob response with status code.
JSONBlob(code int, b []byte) error
// JSONP sends a JSONP response with status code. It uses `callback` to construct
// the JSONP payload.
JSONP(code int, callback string, i any) error
// JSONPBlob sends a JSONP blob response with status code. It uses `callback`
// to construct the JSONP payload.
JSONPBlob(code int, callback string, b []byte) error
// XML sends an XML response with status code.
XML(code int, i any) error
// XMLPretty sends a pretty-print XML with status code.
XMLPretty(code int, i any, indent string) error
// XMLBlob sends an XML blob response with status code.
XMLBlob(code int, b []byte) error
// Blob sends a blob response with status code and content type.
Blob(code int, contentType string, b []byte) error
// Stream sends a streaming response with status code and content type.
Stream(code int, contentType string, r io.Reader) error
// File sends a response with the content of the file.
File(file string) error
// Attachment sends a response as attachment, prompting client to save the
// file.
Attachment(file string, name string) error
// Inline sends a response as inline, opening the file in the browser.
Inline(file string, name string) error
// NoContent sends a response with no body and a status code.
NoContent(code int) error
// Redirect redirects the request to a provided URL with status code.
Redirect(code int, url string) error
// Error invokes the registered global HTTP error handler. Generally used by middleware.
// A side-effect of calling global error handler is that now Response has been committed (sent to the client) and
// middlewares up in chain can not change Response status code or Response body anymore.
//
// Avoid using this method in handlers as no middleware will be able to effectively handle errors after that.
Error(err error)
// Reset resets the context after request completes. It must be called along
// with `Echo#AcquireContext()` and `Echo#ReleaseContext()`.
// See `Echo#ServeHTTP()`
Reset(r *http.Request, w http.ResponseWriter)
// ValidateRequest validates provided request payload `i`. It is usually called after `Context#Bind()`.
// Validator must be registered using `App#SetHttpValidator()`.
ValidateRequest(i any) *HttpValidatorErr
// Log.
TraceID() (val string)
// Log.
Log() *logger
// Api return HTTP(s) API responder.
Api() ApiResponse
}
HttpContext represents the context of the current HTTP(s) request. It holds request and response objects, path, path parameters, data and registered handler. It is abstraction copy from echo.Context.
type HttpHandler ¶
type HttpHandler func(c HttpContext) error
HttpHandler defines a function to serve HTTP(s) requests.
type HttpHandlerChain ¶
type HttpHandlerChain[T HttpRequestPayload] interface { // HandlerWrapper is wrapper function for HTTP(s) handler. HandlerWrapper(c HttpContext) error }
HttpHandlerChain defines HTTP(s) handler wrapper.
type HttpHandlerable ¶
type HttpHandlerable HttpHandler
HttpHandlerable defines HTTP(s) that can be used by user's .
type HttpHandlerableWithPayload ¶
type HttpHandlerableWithPayload[T HttpRequestPayload] func(c HttpContext, p T) error
HttpHandlerableWithPayload same like `HttpHandlerable` but need & use request payload.
type HttpMiddleware ¶
type HttpMiddleware func(next HttpHandler) HttpHandler
HttpMiddleware defines a function to process middleware.
type HttpRequestPayload ¶
type HttpRequestPayload interface {
Validate() error
}
type HttpResponseClientError ¶
type HttpResponseClientError int
HttpResponseClientError defines type of HTTP(s) status response client error.
const ( HttpStatusBadRequest HttpResponseClientError = http.StatusBadRequest HttpStatusPaymentRequired HttpResponseClientError = http.StatusPaymentRequired HttpStatusForbidden HttpResponseClientError = http.StatusForbidden HttpStatusNotFound HttpResponseClientError = http.StatusNotFound HttpStatusMethodNotAllowed HttpResponseClientError = http.StatusMethodNotAllowed HttpStatusNotAcceptable HttpResponseClientError = http.StatusNotAcceptable HttpStatusProxyAuthRequired HttpResponseClientError = http.StatusProxyAuthRequired HttpStatusRequestTimeout HttpResponseClientError = http.StatusRequestTimeout HttpStatusConflict HttpResponseClientError = http.StatusConflict HttpStatusGone HttpResponseClientError = http.StatusGone )
HTTP(s) client error's status codes.
type HttpResponseRedirect ¶
type HttpResponseRedirect int
HttpResponseRedirect defines type of HTTP(s) status response redirect.
const ( HttpStatusMovedPermanently HttpResponseRedirect = http.StatusMovedPermanently HttpStatusFound HttpResponseRedirect = http.StatusFound HttpStatusNotModified HttpResponseRedirect = http.StatusNotModified )
HTTP(s) redirect's status codes.
type HttpResponseServerError ¶
type HttpResponseServerError int
HttpResponseServerError defines type of HTTP(s) status response server error.
const ( HttpStatusInternalServerError HttpResponseServerError = http.StatusInternalServerError HttpStatusNotImplemented HttpResponseServerError = http.StatusNotImplemented HttpStatusBadGateway HttpResponseServerError = http.StatusBadGateway HttpStatusGatewayTimeout HttpResponseServerError = http.StatusGatewayTimeout )
HTTP(s) server error's status codes.
type HttpResponseSuccess ¶
type HttpResponseSuccess int
HttpResponseSuccess defines type of HTTP(s) status response success.
const ( HttpStatusOK HttpResponseSuccess = http.StatusOK HttpStatusCreated HttpResponseSuccess = http.StatusCreated HttpStatusAccepted HttpResponseSuccess = http.StatusAccepted HttpStatusNonAuthoritativeInfo HttpResponseSuccess = http.StatusNonAuthoritativeInfo HttpStatusNoContent HttpResponseSuccess = http.StatusNoContent HttpStatusResetContent HttpResponseSuccess = http.StatusResetContent HttpStatusPartialContent HttpResponseSuccess = http.StatusPartialContent )
HTTP(s) success's status codes.
type HttpRouter ¶
type HttpRouter struct {
// contains filtered or unexported fields
}
HttpRouter defines router for the HTTP server.
func (*HttpRouter) Connect ¶
func (r *HttpRouter) Connect(path string, handler HttpHandlerChain[HttpRequestPayload], middlewares ...HttpMiddleware)
Connect registers a new CONNECT route for a path.
func (*HttpRouter) Delete ¶
func (r *HttpRouter) Delete(path string, handler HttpHandlerChain[HttpRequestPayload], middlewares ...HttpMiddleware)
Delete registers a new DELETE route for a path.
func (*HttpRouter) Get ¶
func (r *HttpRouter) Get(path string, handler HttpHandlerChain[HttpRequestPayload], middlewares ...HttpMiddleware)
Get registers a new GET route for a path.
func (*HttpRouter) Group ¶
func (r *HttpRouter) Group(prefix string, fn func(group *HttpRouter), middlewares ...HttpMiddleware)
Group creates a new router group with prefix.
func (*HttpRouter) Head ¶
func (r *HttpRouter) Head(path string, handler HttpHandlerChain[HttpRequestPayload], middlewares ...HttpMiddleware)
Head registers a new HEAD route for a path.
func (*HttpRouter) Options ¶
func (r *HttpRouter) Options(path string, handler HttpHandlerChain[HttpRequestPayload], middlewares ...HttpMiddleware)
Options registers a new OPTIONS route for a path.
func (*HttpRouter) Patch ¶
func (r *HttpRouter) Patch(path string, handler HttpHandlerChain[HttpRequestPayload], middlewares ...HttpMiddleware)
Patch registers a new PATCH route for a path.
func (*HttpRouter) Post ¶
func (r *HttpRouter) Post(path string, handler HttpHandlerChain[HttpRequestPayload], middlewares ...HttpMiddleware)
Post registers a new POST route for a path.
func (*HttpRouter) Put ¶
func (r *HttpRouter) Put(path string, handler HttpHandlerChain[HttpRequestPayload], middlewares ...HttpMiddleware)
Put registers a new PUT route for a path.
func (*HttpRouter) Trace ¶
func (r *HttpRouter) Trace(path string, handler HttpHandlerChain[HttpRequestPayload], middlewares ...HttpMiddleware)
Trace registers a new TRACE route for a path.
type HttpValidator ¶
type HttpValidator interface {
// Validate is a function to validate the given interface and return error if any.
Validate(a any) *HttpValidatorErr
}
HttpValidator is the interface that wrap the Validate function.
type HttpValidatorErr ¶
type HttpValidatorErr struct {
ErrMandatory error
ErrFormat error
// contains filtered or unexported fields
}
HttpValidatorErr defines http validator error wrap.
func (*HttpValidatorErr) Close ¶
func (e *HttpValidatorErr) Close()
Close releases instance to the pool.
func (*HttpValidatorErr) Error ¶
func (e *HttpValidatorErr) Error() string
Error implements error interface.
type ModuleLoader ¶
type ModuleLoader interface {
Load() []Module
}
ModuleLoader is module loader interface.
type Numeric ¶
type Numeric interface {
int | int8 | int16 | int32 | int64 |
uint | uint8 | uint16 | uint32 | uint64 |
float32 | float64
}
Numeric custom type.
type Supervisor ¶
type Supervisor interface {
// ListenSignals returns signal(s) that must be listened to do gracefully stop.
ListenSignals() []os.Signal
// Run is the main method responsible for running the application.
Run(app *App)
}
Supervisor is process manager that manage application process.
type SupervisorGraceful ¶
type SupervisorGraceful struct {
// Signals that must be listened to do gracefully stop.
Signals []os.Signal
// HookStart will be executed before the application start.
HookStart func()
// HookStop will be executed before the application stop.
HookStop func()
// BinaryFilePath location of the binary file.
BinaryFilePath string
// Graceful shutdown or restart signal.
GracefulRestartSignal os.Signal
// Graceful shutdown or restart interval seconds.
GracefulInterval int
// contains filtered or unexported fields
}
SupervisorGraceful implement Supervisor and manage the application gracefully.
func (*SupervisorGraceful) ListenSignals ¶
func (s *SupervisorGraceful) ListenSignals() []os.Signal
func (*SupervisorGraceful) Run ¶
func (s *SupervisorGraceful) Run(app *App)
type SupervisorNon ¶
type SupervisorNon struct {
// Signals that must be listened to do gracefully stop.
Signals []os.Signal
// HookStart will be executed before the application start.
HookStart func()
// HookStop will be executed before the application stop.
HookStop func()
}
SupervisorNon implement Supervisor but does not manage the application restart gracefully.
func (*SupervisorNon) ListenSignals ¶
func (s *SupervisorNon) ListenSignals() []os.Signal
func (*SupervisorNon) Run ¶
func (s *SupervisorNon) Run(app *App)
Source Files
¶
- config.go
- const.go
- context.go
- dependency.go
- factory.go
- http.go
- http_api_response.go
- http_const.go
- http_context.go
- http_error.go
- http_handler_chain_impl.go
- http_response.go
- http_router.go
- http_types.go
- http_validator.go
- http_validator_impl.go
- lifecycle.go
- logger.go
- qore.go
- supervisor_graceful.go
- supervisor_non.go
- types.go
- util_slice.go
- util_string.go
- util_validation.go