server

package
v0.3.14 Latest Latest
Warning

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

Go to latest
Published: Feb 2, 2024 License: GPL-3.0 Imports: 27 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LogLevelDebug       = "debug"
	LogLevelInfo        = "info"
	ContextKeyRequestID = "request_id"
)
View Source
const (
	ConfigDBURI     = "db_uri"
	ConfigDBMaxConn = "db_max_connections"
)

Config property names

View Source
const (
	ConfigPort             = "port"
	ConfigReadTimeout      = "readTimeout"
	ConfigWriteTimeout     = "writeTimeout"
	ConfigLogLevel         = "loglevel"
	ConfigEnableProfiling  = "enable_profiling"
	ConfigEnablePrometheus = "enable_prometheus"
)

All config properties required for the server to run

View Source
const (
	SnapshotKey = "--snapshot--"
)

Variables

This section is empty.

Functions

func GetJwtAuth added in v0.2.10

func GetJwtAuth(issuer string, customValidator func(claims jwt.MapClaims) error) func(ctx *Context) error

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

func CreateConfig(path string, name string, properties []string) Config

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

func (c *Config) Get(property string) string

Get returns a cached property value. Panics if the property doesn't exist

func (*Config) GetDuration

func (c *Config) GetDuration(property string) (time.Duration, error)

GetDuration fetches the property as string and attempts at parsing it as duration string

func (*Config) GetInt

func (c *Config) GetInt(property string) int

GetInt fetches the property as string and attempts at parsing it as duration string

func (*Config) LoadProperties

func (c *Config) LoadProperties(properites []string)

LoadProperties attempts to load all provided properties from the config file into memory

func (*Config) SetProperty added in v0.2.0

func (c *Config) SetProperty(key string, value string)

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

func (ctx *Context) GetRequestBody() ([]byte, error)

GetRequestBody readx the full body and returns it

func (*Context) GetRequestContextValue added in v0.3.7

func (ctx *Context) GetRequestContextValue(key string) any

func (*Context) GetRequestID added in v0.3.7

func (ctx *Context) GetRequestID() string

func (*Context) GetService

func (ctx *Context) GetService(name string) interface{}

GetService retrieves the specified service by name

func (*Context) LogDebug added in v0.2.7

func (ctx *Context) LogDebug(msg string)

LogDebug logs an debug message

func (*Context) LogDebugf added in v0.3.13

func (ctx *Context) LogDebugf(format string, args ...any)

LogInfof logs an debug message with formatting

func (*Context) LogError

func (ctx *Context) LogError(msg string)

LogError logs an error

func (*Context) LogErrorf added in v0.3.13

func (ctx *Context) LogErrorf(format string, args ...any)

LogErrorf logs an error with formatting

func (*Context) LogInfo

func (ctx *Context) LogInfo(msg string)

LogInfo logs an info message

func (*Context) LogInfof added in v0.3.13

func (ctx *Context) LogInfof(format string, args ...any)

LogInfof logs an info message with formatting

func (*Context) SendGenericResponse

func (ctx *Context) SendGenericResponse(code int, response []byte, contentType string)

SendGenericResponse sends the response using the context if the response was not sent already.

func (*Context) SendHTMLResponse

func (ctx *Context) SendHTMLResponse(code int, response []byte)

SendHTMLResponse uses SendGenericResponse but sets the content type to text/html

func (*Context) SendJSONResponse

func (ctx *Context) SendJSONResponse(code int, response []byte)

SendJSONResponse uses SendGenericResponse but sets the content type to application/json

func (*Context) SendJsonError added in v0.3.0

func (ctx *Context) SendJsonError(err error)

SendJsonError sends a properly formatted error response

func (*Context) SendRedirect added in v0.2.9

func (ctx *Context) SendRedirect(newurl string, statusCode int)

func (*Context) SendResponseHeader

func (ctx *Context) SendResponseHeader(header string, value string)

SendResponseHeader sends the response header

func (*Context) SetRequestBodyManually

func (ctx *Context) SetRequestBodyManually(body []byte)

SetRequestBodyManually sets the body. Mainly used for testing

func (*Context) SetRequestContextValue added in v0.3.7

func (ctx *Context) SetRequestContextValue(key string, value any)

func (*Context) SetRequestID added in v0.3.7

func (ctx *Context) SetRequestID(id string)

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 DBconfig

type DBconfig struct {
	DbURI              string
	DbMaxDBConnections int
}

DBconfig holds all relevant db configurations

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 Metric

type Metric string

Metric enum of all available metrics

type Repository

type Repository struct {
	DB *gorm.DB
	// contains filtered or unexported fields
}

Repository provides access to the DB and prepared statements

func CreateRepository

func CreateRepository(c *Config) *Repository

CreateRepository intizializes a 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

func (s *Server) GetMainHandler() http.Handler

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 (s *Server) GetService(name string) interface{}

func (*Server) InitNonRequestContext added in v0.3.12

func (s *Server) InitNonRequestContext() *Context

func (*Server) RegisterService

func (s *Server) RegisterService(name string, service interface{})

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.

func (*Server) Start

func (s *Server) Start()

Start starts the previously initialized server

type StatusInformation

type StatusInformation struct {
	Stats map[string]int
	// contains filtered or unexported fields
}

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

Jump to

Keyboard shortcuts

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