Documentation
¶
Index ¶
- Constants
- func GetJwtAuth(issuer string, customValidator func(claims jwt.MapClaims) error) func(ctx *Context) error
- func GetJwtAuthFromQuery(issuer string, customValidator func(claims jwt.MapClaims) error, ...) func(ctx *Context) error
- type Config
- type Context
- func (ctx *Context) GetRequestBody() ([]byte, error)
- func (ctx *Context) GetRequestContextValue(key string) any
- func (ctx *Context) GetRequestID() string
- func (ctx *Context) GetService(name string) interface{}
- func (ctx *Context) LogDebug(msg string)
- func (ctx *Context) LogDebugf(format string, args ...any)
- func (ctx *Context) LogError(msg string)
- func (ctx *Context) LogErrorf(format string, args ...any)
- func (ctx *Context) LogInfo(msg string)
- func (ctx *Context) LogInfof(format string, args ...any)
- func (ctx *Context) SendGenericResponse(code int, response []byte, contentType string)
- func (ctx *Context) SendHTMLResponse(code int, response []byte)
- func (ctx *Context) SendJSONResponse(code int, response []byte)
- func (ctx *Context) SendJsonError(err error)
- func (ctx *Context) SendRedirect(newurl string, statusCode int)
- func (ctx *Context) SendResponseHeader(header string, value string)
- func (ctx *Context) SetRequestBodyManually(body []byte)
- func (ctx *Context) SetRequestContextValue(key string, value any)
- func (ctx *Context) SetRequestID(id string)
- type Controller
- type ControllerProvider
- type DBconfig
- type JSONErrorResponse
- type JSONWebKeys
- type Jwks
- type Metric
- type Repository
- type Server
- func (s *Server) GetControllers() []Controller
- func (s *Server) GetMainHandler() http.Handler
- func (s *Server) GetRepository() *Repository
- func (s *Server) GetService(name string) interface{}
- func (s *Server) InitNonRequestContext() *Context
- func (s *Server) RegisterService(name string, service interface{})
- func (s *Server) SetRepository(repo *Repository)
- func (s *Server) Start()
- type StatusInformation
Constants ¶
const ( LogLevelDebug = "debug" LogLevelInfo = "info" ContextKeyRequestID = "request_id" )
const ( ConfigDBURI = "db_uri" ConfigDBMaxConn = "db_max_connections" )
Config property names
const ( ConfigPort = "port" ConfigReadTimeout = "readTimeout" ConfigWriteTimeout = "writeTimeout" ConfigLogLevel = "loglevel" ConfigEnableProfiling = "enable_profiling" ConfigEnablePrometheus = "enable_prometheus" )
All config properties required for the server to run
const (
SnapshotKey = "--snapshot--"
)
Variables ¶
This section is empty.
Functions ¶
func GetJwtAuth ¶ added in v0.2.10
Types ¶
type Config ¶
type Config struct {
// contains filtered or unexported fields
}
Config Central access point to all config properties. The basic principle is that we want to fail on startup if a config property is missing.
func CreateConfig ¶
CreateConfig creates a new Config object and initializes it with the given config file ref. To follow the principle described for Config, the config file is only read here. If another key is requested later on then the application will fail. So properties should contain every key that will ever be needed.
func (*Config) GetDuration ¶
GetDuration fetches the property as string and attempts at parsing it as duration string
func (*Config) GetInt ¶
GetInt fetches the property as string and attempts at parsing it as duration string
func (*Config) LoadProperties ¶
LoadProperties attempts to load all provided properties from the config file into memory
func (*Config) SetProperty ¶ added in v0.2.0
SetProperty Allows to programmatically add properties or change their value if the key already exists. Only strings are supported for storage. But they can be converted with the appropriate Get methods.
type Context ¶
type Context struct { Server *Server Request *http.Request Repository *Repository IsResponseSent bool ResponseCode int StatusInformation *StatusInformation Subdomain string ControllerProvider ControllerProvider Controller *Controller LogLevel string // contains filtered or unexported fields }
Context intantiated for every request
func (*Context) GetRequestBody ¶
GetRequestBody readx the full body and returns it
func (*Context) GetRequestContextValue ¶ added in v0.3.7
func (*Context) GetRequestID ¶ added in v0.3.7
func (*Context) GetService ¶
GetService retrieves the specified service by name
func (*Context) SendGenericResponse ¶
SendGenericResponse sends the response using the context if the response was not sent already.
func (*Context) SendHTMLResponse ¶
SendHTMLResponse uses SendGenericResponse but sets the content type to text/html
func (*Context) SendJSONResponse ¶
SendJSONResponse uses SendGenericResponse but sets the content type to application/json
func (*Context) SendJsonError ¶ added in v0.3.0
SendJsonError sends a properly formatted error response
func (*Context) SendRedirect ¶ added in v0.2.9
func (*Context) SendResponseHeader ¶
SendResponseHeader sends the response header
func (*Context) SetRequestBodyManually ¶
SetRequestBodyManually sets the body. Mainly used for testing
func (*Context) SetRequestContextValue ¶ added in v0.3.7
func (*Context) SetRequestID ¶ added in v0.3.7
type Controller ¶
type Controller struct { Name string Metric string Path string HandlesSubpaths bool Methods []string IsSecured bool AuthFunc func(ctx *Context) error ControllerFunc func(ctx *Context) Description string // contains filtered or unexported fields }
Controller base type of all controllers
var StatusController Controller = Controller{ Name: "StatusController", Metric: "status", Path: "/status", Methods: []string{"GET"}, IsSecured: false, ControllerFunc: func(ctx *Context) { stats := ctx.StatusInformation.snapshot() html := strings.Builder{} html.WriteString("<html><h1>Status</h1><br/>") html.WriteString(fmt.Sprintf("Running since: %s<br/><br/>", ctx.StatusInformation.start.Format("2006-01-02 15:04:05"))) html.WriteString( `<table> <tr align="left"> <th>Controller Name</th> <th>Methods</th> <th>Path</th> <th>Invokation Count</th> <th>Description</th> </tr>`) for _, ctr := range ctx.Server.GetControllers() { html.WriteString(fmt.Sprintf("<tr><td>%s</td><td>%+v</td><td>%s</td><td align='center'>%d</td><td>%s</td></tr>", ctr.Name, ctr.Methods, ctr.Path, stats[ctr.Metric], ctr.Description)) delete(stats, ctr.Metric) } html.WriteString("</table>\n") html.WriteString("<p><h2>Non Controller Metrics</h2></p>\n") html.WriteString( `<table> <tr align="left"> <th>Metric</th> <th>Value</th> </tr>`) sortedMetrics := make([]string, 0, len(stats)) for metric, _ := range stats { sortedMetrics = append(sortedMetrics, metric) } slices.Sort(sortedMetrics) for _, metric := range sortedMetrics { html.WriteString(fmt.Sprintf("<tr><td>%s</td><td align='center'>%d</td></tr>", metric, stats[metric])) } html.WriteString("</table>\n") ctx.SendHTMLResponse(http.StatusOK, []byte(html.String())) }, }
StatusController shows status page
func (*Controller) Execute ¶
func (ctr *Controller) Execute(ctx *Context)
Execute executes the controller in the given context
type ControllerProvider ¶
type ControllerProvider interface {
GetControllers() []Controller
}
ControllerProvider Interfice providing access the list of controllers from another module. If a controller provider requires configuration then it is expected to export the parameters as fields and the function instantiating the server is responsible to fill them. The Config can be used for convenience.
type JSONErrorResponse ¶ added in v0.3.0
type JSONErrorResponse struct { Code int `json:"code"` Message string `json:"message"` LogMessage string `json:"-"` RequestID string `json:"request_id"` }
JSONErrorResponse General format of error responses
func ErrToJSONErrorResponsePreserveCode ¶ added in v0.3.0
func ErrToJSONErrorResponsePreserveCode(err error, message string) JSONErrorResponse
func (JSONErrorResponse) Error ¶ added in v0.3.0
func (jer JSONErrorResponse) Error() string
type JSONWebKeys ¶
type JSONWebKeys struct { Kty string `json:"kty"` Kid string `json:"kid"` Use string `json:"use"` N string `json:"n"` E string `json:"e"` X5c []string `json:"x5c"` }
JSONWebKeys used to marshal the key response from Auth0
type Jwks ¶
type Jwks struct {
Keys []JSONWebKeys `json:"keys"`
}
Jwks used to marshal the key response from Auth0
type Repository ¶
Repository provides access to the DB and prepared statements
func CreateRepository ¶
func CreateRepository(c *Config) *Repository
CreateRepository intizializes a repository
func CreateRepositoryFromParams ¶ added in v0.4.3
func CreateRepositoryFromParams(dbURI string, maxConn int) *Repository
func (*Repository) RunMigrations ¶
func (r *Repository) RunMigrations(entities []interface{})
RunMigrations migrates all provided entities which must be gorm compatible entities
type Server ¶
type Server struct { LogLevel string // contains filtered or unexported fields }
Server Generic server who is able to load a list of controllers from multiple ControllerProviders
func BlankServer ¶ added in v0.3.6
func BlankServer() *Server
func CreateServer ¶
func CreateServer(config Config, ctrProviders []ControllerProvider) *Server
CreateServer Factory method to create a Server instance. This is meant to be used by main methods and provide the list of ControllerProviders the server instance is supposed to serve
func CreateServerWithPrefix ¶ added in v0.3.2
func CreateServerWithPrefix(config Config, ctrProviders []ControllerProvider, pathPrefix string) *Server
func (*Server) GetControllers ¶
func (s *Server) GetControllers() []Controller
GetControllers returns all controllers of the controller provider
func (*Server) GetMainHandler ¶ added in v0.1.3
GetMainHandler Gives access to the mux router for testing purposes
func (*Server) GetRepository ¶ added in v0.3.1
func (s *Server) GetRepository() *Repository
func (*Server) GetService ¶ added in v0.3.1
func (*Server) InitNonRequestContext ¶ added in v0.3.12
func (*Server) RegisterService ¶
RegisterService registers a service to the server
func (*Server) SetRepository ¶
func (s *Server) SetRepository(repo *Repository)
SetRepository sets the repository if one is being used.
type StatusInformation ¶
StatusInformation struct holding all status metrics. Meant to be instantiated once per server
func CreateStatusInfo ¶
func CreateStatusInfo() *StatusInformation
CreateStatusInfo factory to create a new status info and start thread to process incoming metrics
func (*StatusInformation) IncrementMetric ¶
func (s *StatusInformation) IncrementMetric(m string)
IncrementMetric increments given metric by one. Threadsafe
func (*StatusInformation) SetMetric ¶ added in v0.3.13
func (s *StatusInformation) SetMetric(metric string, value int)
SetMetric Sets the given metric to the provided value. Threadsafe