sapi

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2023 License: MIT Imports: 18 Imported by: 0

README

sapi

Opinionated golang API scaffolding using the slate application framework

  • sapi
    • cache
      • store
        • inmemory
        • memcached
        • bmemcached
        • redis
    • envelope
    • rest
      • envelopemw
      • logmw
        • request
          • json
          • xml
        • response
          • json
          • xml
    • validation

Documentation

Overview

Package sapi @todo

Index

Constants

View Source
const (
	// RestContainerID defines a base id of all other rest
	// module instances registered in the application container.
	RestContainerID = slate.ContainerID + ".rest"

	// RestEndpointRegisterTag @todo doc
	RestEndpointRegisterTag = RestContainerID + ".endpoints"

	// RestAllEndpointRegistersContainerID @todo doc
	RestAllEndpointRegistersContainerID = RestEndpointRegisterTag + ".all"

	// RestProcessContainerID @todo doc.
	RestProcessContainerID = RestContainerID + ".process"

	// RestLoaderContainerID @todo doc.
	RestLoaderContainerID = RestContainerID + ".loader"

	// RestEnvID defines the rest module base environment variable name.
	RestEnvID = slate.EnvID + "_REST"
)
View Source
const (
	// RestEnvelopeMwContainerID defines the default id used to register
	// the application envelope middleware and related services.
	RestEnvelopeMwContainerID = RestContainerID + ".envelope.mw"

	// RestEnvelopeMwEnvID defines the envelope middleware module
	// base environment variable name.
	RestEnvelopeMwEnvID = RestEnvID + "_ENVELOPE_MW"
)
View Source
const (
	// RestLogMwContainerID defines the default id used to register
	// the application log middleware and related services.
	RestLogMwContainerID = RestContainerID + ".log.mw"

	// RestLogMwEnvID defines the log middleware module base
	// environment variable name.
	RestLogMwEnvID = RestEnvID + "_LOG_MW"
)
View Source
const (
	// ValidationContainerID defines the id to be used
	// as the container registration id of a validation.
	ValidationContainerID = slate.ContainerID + ".validation"

	// ValidationTranslatorContainerID defines the id to be used
	// as the container registration id of a translator.
	ValidationTranslatorContainerID = ValidationContainerID + ".translator"

	// ValidationUniversalTranslatorContainerID defines the id to be used
	// as the container registration id of a universal translator.
	ValidationUniversalTranslatorContainerID = ValidationContainerID + ".universal"

	// ValidationParserContainerID defines the id to be used
	// as the container registration id of an error parser instance.
	ValidationParserContainerID = ValidationContainerID + ".parser"

	// ValidationEnvID defines the validation module base environment variable name.
	ValidationEnvID = slate.EnvID + "_VALIDATION"
)

Variables

View Source
var (
	// RestConfigPath defines the configuration location where is
	// defined the REST service configuration.
	RestConfigPath = slate.EnvString(RestEnvID+"_CONFIG_PATH", "slate.api.rest")

	// RestWatchdogName defines the default REST service watchdog name.
	RestWatchdogName = slate.EnvString(RestEnvID+"_WATCHDOG_NAME", "rest")

	// RestPort defines the default rest service port.
	RestPort = slate.EnvInt(RestEnvID+"_PORT", 80)

	// RestLogChannel defines the default logging channel.
	RestLogChannel = slate.EnvString(RestEnvID+"_LOG_CHANNEL", "rest")

	// RestLogLevel defines the default logging level.
	RestLogLevel = slate.EnvString(RestEnvID+"_LOG_LEVEL", "info")

	// RestLogStartMessage defines the default service start logging message.
	RestLogStartMessage = slate.EnvString(RestEnvID+"_LOG_START_MESSAGE", "[service:rest] service starting ...")

	// RestLogErrorMessage defines the default service error logging message.
	RestLogErrorMessage = slate.EnvString(RestEnvID+"_LOG_ERROR_MESSAGE", "[service:rest] service error")

	// RestLogEndMessage defines the default service end logging message.
	RestLogEndMessage = slate.EnvString(RestEnvID+"_LOG_END_MESSAGE", "[service:rest] service terminated")
)
View Source
var (
	// RestEnvelopeMwConfigPathServiceID defines the config path that used to store the
	// application service identifier.
	RestEnvelopeMwConfigPathServiceID = slate.EnvString(RestEnvelopeMwEnvID+"_CONFIG_PATH_SERVICE_ID", "slate.api.rest.service.id")

	// RestEnvelopeMwConfigPathFormatAcceptList defines the config path that used toLogAcceptListErrorMessage
	// store the application accepted mime types formats.
	RestEnvelopeMwConfigPathFormatAcceptList = slate.EnvString(RestEnvelopeMwEnvID+"_CONFIG_PATH_FORMAT_ACCEPT_LIST", "slate.api.rest.accept")

	// RestEnvelopeMwConfigPathEndpointID defines the format of the configuration
	// path where the endpoint identification number can be retrieved.
	RestEnvelopeMwConfigPathEndpointID = slate.EnvString(RestEnvelopeMwEnvID+"_CONFIG_PATH_ENDPOINT_ID", "slate.api.rest.endpoints.%s.id")

	// RestEnvelopeMwLogLevel @todo doc
	RestEnvelopeMwLogLevel = slate.EnvString(RestEnvelopeMwEnvID+"_LOG_LEVEL", "error")

	// RestEnvelopeMwLogChannel @todo doc
	RestEnvelopeMwLogChannel = slate.EnvString(RestEnvelopeMwEnvID+"_LOG_CHANNEL", "rest")

	// RestEnvelopeMwLogServiceErrorMessage @todo doc
	RestEnvelopeMwLogServiceErrorMessage = slate.EnvString(RestEnvelopeMwEnvID+"_LOG_SERVICE_ERROR_MESSAGE", "Invalid service id")

	// RestEnvelopeMwLogAcceptListErrorMessage @todo doc
	RestEnvelopeMwLogAcceptListErrorMessage = slate.EnvString(RestEnvelopeMwEnvID+"_LOG_ACCEPT_LIST_ERROR_MESSAGE", "Invalid accept list")

	// RestEnvelopeMwLogEndpointErrorMessage @todo doc
	RestEnvelopeMwLogEndpointErrorMessage = slate.EnvString(RestEnvelopeMwEnvID+"_LOG_ENDPOINT_ERROR_MESSAGE", "Invalid endpoint id")

	// RestEnvelopeMwContextField @todo doc
	RestEnvelopeMwContextField = slate.EnvString(RestEnvelopeMwEnvID+"_CONTEXT_FIELD", "sapi_response")
)
View Source
var (
	// RestLogMwRequestChannel defines the channel id to be used when
	// the log middleware sends the request logging signal to the logger
	// instance.
	RestLogMwRequestChannel = slate.EnvString(RestLogMwEnvID+"_REQUEST_CHANNEL", "rest")

	// RestLogMwRequestLevel defines the logging level to be used when
	// the log middleware sends the request logging signal to the logger
	// instance.
	RestLogMwRequestLevel = envToLogLevel(RestLogMwEnvID+"_REQUEST_LEVEL", slate.DEBUG)

	// RestLogMwRequestMessage defines the request event logging message to
	// be used when the log middleware sends the logging signal to the logger
	// instance.
	RestLogMwRequestMessage = slate.EnvString(RestLogMwEnvID+"_REQUEST_MESSAGE", "Request")

	// RestLogMwResponseChannel defines the channel id to be used when the
	// log middleware sends the response logging signal to the logger instance.
	RestLogMwResponseChannel = slate.EnvString(RestLogMwEnvID+"_RESPONSE_CHANNEL", "rest")

	// RestLogMwResponseLevel defines the logging level to be used when the
	// log middleware sends the response logging signal to the logger instance.
	RestLogMwResponseLevel = envToLogLevel(RestLogMwEnvID+"_RESPONSE_LEVEL", slate.INFO)

	// RestLogMwResponseMessage defines the response event logging message
	// to be used when the log middleware sends the logging signal to the
	// logger instance.
	RestLogMwResponseMessage = slate.EnvString(RestLogMwEnvID+"_RESPONSE_MESSAGE", "Response")
)
View Source
var (
	// ErrValidationTranslatorNotFound defines an error that denotes
	// that a required error translator was not found.
	ErrValidationTranslatorNotFound = fmt.Errorf("validation translator not found")
)
View Source
var (
	// ValidationLocale defines the default locale string to be used when
	// instantiating the translator.
	ValidationLocale = slate.EnvString(ValidationEnvID+"_LOCALE", "en")
)

Functions

func NewValidationTranslator

func NewValidationTranslator(
	universalTranslator *ut.UniversalTranslator,
) (ut.Translator, error)

NewValidationTranslator @todo doc

func NewValidationUniversalTranslator

func NewValidationUniversalTranslator() *ut.UniversalTranslator

NewValidationUniversalTranslator @todo doc

func RestSetResponse added in v0.2.0

func RestSetResponse(
	ctx *gin.Context,
	response interface{},
) *gin.Context

RestSetResponse @todo doc

Types

type Envelope

type Envelope struct {
	XMLName    xml.Name            `json:"-" xml:"envelope"`
	StatusCode int                 `json:"-" xml:"-"`
	Status     *EnvelopeStatus     `json:"status" xml:"status"`
	ListReport *EnvelopeListReport `json:"report,omitempty" xml:"report,omitempty"`
	Data       interface{}         `json:"data,omitempty" xml:"data,omitempty"`
}

Envelope identifies the structure of a response structured format.

func NewEnvelope

func NewEnvelope(
	statusCode int,
	data interface{},
	listReport ...*EnvelopeListReport,
) *Envelope

NewEnvelope instantiates a new response data envelope structure

func (*Envelope) AddError

func (s *Envelope) AddError(
	e *EnvelopeStatusError,
) *Envelope

AddError add a new error to the response envelope instance

func (*Envelope) GetStatusCode

func (s *Envelope) GetStatusCode() int

GetStatusCode returned the stored enveloped response status code

func (*Envelope) SetEndpoint

func (s *Envelope) SetEndpoint(
	val int,
) *Envelope

SetEndpoint assign the endpoint identifier to all stored error codes

func (*Envelope) SetListReport

func (s *Envelope) SetListReport(
	listReport *EnvelopeListReport,
) *Envelope

SetListReport assign the list report to the envelope

func (*Envelope) SetService

func (s *Envelope) SetService(
	val int,
) *Envelope

SetService assign the service identifier to all stored error codes

type EnvelopeListReport

type EnvelopeListReport struct {
	Search string `json:"search" xml:"search"`
	Start  uint   `json:"start" xml:"start"`
	Count  uint   `json:"count" xml:"count"`
	Total  uint   `json:"total" xml:"total"`
	Prev   string `json:"prev" xml:"prev"`
	Next   string `json:"next" xml:"next"`
}

EnvelopeListReport defines the structure of a response list report containing all the request information, but also the total amount of filtering records and links for the previous and next pages

func NewEnvelopeListReport

func NewEnvelopeListReport(
	search string,
	start,
	count,
	total uint,
) *EnvelopeListReport

NewEnvelopeListReport instantiates a new response list report by populating the prev and next link information regarding the given filtering information

type EnvelopeStatus

type EnvelopeStatus struct {
	Success bool                    `json:"success" xml:"success"`
	Errors  EnvelopeStatusErrorList `json:"error" xml:"error"`
}

EnvelopeStatus defines the structure to manipulate a response status information structure.

func NewEnvelopeStatus

func NewEnvelopeStatus() *EnvelopeStatus

NewEnvelopeStatus instantiates a new request result status structure.

func (*EnvelopeStatus) AddError

AddError append a new error to the status error list

func (*EnvelopeStatus) SetEndpoint

func (s *EnvelopeStatus) SetEndpoint(
	val int,
) *EnvelopeStatus

SetEndpoint assign an endpoint code to all stored error.

func (*EnvelopeStatus) SetService

func (s *EnvelopeStatus) SetService(
	val int,
) *EnvelopeStatus

SetService assign a service code to all stored error.

type EnvelopeStatusError

type EnvelopeStatusError struct {
	Service  int    `json:"-" xml:"-"`
	Endpoint int    `json:"-" xml:"-"`
	Param    int    `json:"-" xml:"-"`
	Error    string `json:"-" xml:"-"`
	Code     string `json:"code" xml:"code"`
	Message  string `json:"message" xml:"message"`
}

EnvelopeStatusError defines the structure to manipulate an error structure that hold the information of an execution error and be assigned to the response status error list.

func NewEnvelopeStatusError

func NewEnvelopeStatusError(
	e any,
	msg string,
) *EnvelopeStatusError

NewEnvelopeStatusError instantiates a new error instance.

func (*EnvelopeStatusError) GetCode

func (e *EnvelopeStatusError) GetCode() string

GetCode retrieves the composed code of the error

func (*EnvelopeStatusError) GetMessage

func (e *EnvelopeStatusError) GetMessage() string

GetMessage retrieves the message associated to the error

func (*EnvelopeStatusError) SetEndpoint

func (e *EnvelopeStatusError) SetEndpoint(
	val int,
) *EnvelopeStatusError

SetEndpoint assigns an endpoint code value to the error.

func (*EnvelopeStatusError) SetError

func (e *EnvelopeStatusError) SetError(
	err any,
) *EnvelopeStatusError

SetError assigns a error code value to the error.

func (*EnvelopeStatusError) SetMessage

func (e *EnvelopeStatusError) SetMessage(
	msg string,
) *EnvelopeStatusError

SetMessage assigns a message to the error.

func (*EnvelopeStatusError) SetParam

func (e *EnvelopeStatusError) SetParam(
	param int,
) *EnvelopeStatusError

SetParam assigns a parameter code value to the error.

func (*EnvelopeStatusError) SetService

func (e *EnvelopeStatusError) SetService(
	val int,
) *EnvelopeStatusError

SetService assigns a service code value to the error.

type EnvelopeStatusErrorList

type EnvelopeStatusErrorList []*EnvelopeStatusError

EnvelopeStatusErrorList defines a type of data that holds a list of error structures.

func (EnvelopeStatusErrorList) MarshalXML

func (s EnvelopeStatusErrorList) MarshalXML(
	e *xml.Encoder,
	start xml.StartElement,
) error

MarshalXML serialize the error list into a xml string

type RestEndpointRegister

type RestEndpointRegister interface {
	Reg(engine RestEngine) error
}

RestEndpointRegister defines an interface to an instance that is able to register endpoints to the REST engine/service

type RestEngine

type RestEngine interface {
	gin.IRoutes
	gin.IRouter

	Handler() http.Handler
	Delims(left string, right string) *gin.Engine
	SecureJsonPrefix(prefix string) *gin.Engine
	LoadHTMLGlob(pattern string)
	LoadHTMLFiles(files ...string)
	SetHTMLTemplate(templ *template.Template)
	SetFuncMap(funcMap template.FuncMap)
	NoRoute(handlers ...gin.HandlerFunc)
	NoMethod(handlers ...gin.HandlerFunc)
	Use(middleware ...gin.HandlerFunc) gin.IRoutes
	Routes() (routes gin.RoutesInfo)
	Run(addr ...string) (err error)
	SetTrustedProxies(trustedProxies []string) error
	RunTLS(addr string, certFile string, keyFile string) (err error)
	RunUnix(file string) (err error)
	RunFd(fd int) (err error)
	RunListener(listener net.Listener) (err error)
	ServeHTTP(w http.ResponseWriter, req *http.Request)
	HandleContext(c *gin.Context)
}

RestEngine interface for the gin-gonic engine object.

type RestEnvelopeMwGenerator added in v0.2.0

type RestEnvelopeMwGenerator func(string) (RestMiddleware, error)

RestEnvelopeMwGenerator @todo doc

func NewRestEnvelopeMwGenerator added in v0.2.0

func NewRestEnvelopeMwGenerator(
	config *slate.Config,
	logger *slate.Log,
) (RestEnvelopeMwGenerator, error)

NewRestEnvelopeMwGenerator returns a middleware generator function based on the application configuration. This middleware generator function should be called with the corresponding endpoint name, so it can generate the appropriate middleware function.

type RestEnvelopeMwServiceRegister added in v0.2.0

type RestEnvelopeMwServiceRegister struct {
	slate.ServiceRegister
}

RestEnvelopeMwServiceRegister defines the default envelope provider to be used on the application initialization to register the file system adapter service.

func NewRestEnvelopeMwServiceRegister added in v0.3.0

func NewRestEnvelopeMwServiceRegister(
	app ...*slate.App,
) *RestEnvelopeMwServiceRegister

NewRestEnvelopeMwServiceRegister will generate a new registry instance

func (RestEnvelopeMwServiceRegister) Provide added in v0.2.0

Provide will add to the container a new file system adapter instance.

type RestLoader

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

RestLoader @todo doc

func NewRestLoader

func NewRestLoader(
	engine RestEngine,
	registers []RestEndpointRegister,
) (*RestLoader, error)

NewRestLoader @todo doc

func (*RestLoader) Load

func (l *RestLoader) Load() error

Load @todo doc

type RestLogMwGenerator added in v0.3.0

type RestLogMwGenerator func(statusCode int) RestMiddleware

RestLogMwGenerator @todo doc

func NewRestLogMwGenerator added in v0.3.0

func NewRestLogMwGenerator(
	logger *slate.Log,
	requestReader RestLogMwRequestReader,
	responseReader RestLogMwResponseReader,
) (RestLogMwGenerator, error)

NewRestLogMwGenerator @todo doc

type RestLogMwRequestReader added in v0.3.0

type RestLogMwRequestReader func(ctx *gin.Context) (slate.LogContext, error)

RestLogMwRequestReader defines the function used by the middleware that compose the logging request context object.

func NewRestLogMwRequestReader added in v0.3.0

func NewRestLogMwRequestReader() RestLogMwRequestReader

NewRestLogMwRequestReader is the default function used to parse the request context information.

func NewRestLogMwRequestReaderJSONDecorator added in v0.3.0

func NewRestLogMwRequestReaderJSONDecorator(
	reader RestLogMwRequestReader,
	model interface{},
) (RestLogMwRequestReader, error)

NewRestLogMwRequestReaderJSONDecorator will instantiate a new request event context reader JSON decorator used to parse the request body as a JSON and add the parsed content into the logging data.

func NewRestLogMwRequestReaderXMLDecorator added in v0.3.0

func NewRestLogMwRequestReaderXMLDecorator(
	reader RestLogMwRequestReader,
	model interface{},
) (RestLogMwRequestReader, error)

NewRestLogMwRequestReaderXMLDecorator will instantiate a new request event context reader XML decorator used to parse the request body as an XML and add the parsed content into the logging data.

type RestLogMwResponseReader added in v0.3.0

type RestLogMwResponseReader func(ctx *gin.Context, writer gin.ResponseWriter, statusCode int) (slate.LogContext, error)

RestLogMwResponseReader defines the interface methods of a response context reader used to compose the data to be sent to the logger on a response event.

func NewRestLogMwResponseReader added in v0.3.0

func NewRestLogMwResponseReader() RestLogMwResponseReader

NewRestLogMwResponseReader @todo doc.

func NewRestLogMwResponseReaderJSONDecorator added in v0.3.0

func NewRestLogMwResponseReaderJSONDecorator(
	reader RestLogMwResponseReader,
	model interface{},
) (RestLogMwResponseReader, error)

NewRestLogMwResponseReaderJSONDecorator will instantiate a new response event context reader JSON decorator used to parse the response body as a JSON and add the parsed content into the logging data.

func NewRestLogMwResponseReaderXMLDecorator added in v0.3.0

func NewRestLogMwResponseReaderXMLDecorator(
	reader RestLogMwResponseReader,
	model interface{},
) (RestLogMwResponseReader, error)

NewRestLogMwResponseReaderXMLDecorator will instantiate a new response event context reader XML decorator used to parse the response body as an XML and add the parsed content into the logging data.

type RestLogMwServiceRegister added in v0.3.0

type RestLogMwServiceRegister struct {
	slate.ServiceRegister
}

RestLogMwServiceRegister defines the default envelope provider to be used on the application initialization to register the file system adapter service.

func NewRestLogMwServiceRegister added in v0.3.0

func NewRestLogMwServiceRegister(
	app ...*slate.App,
) *RestLogMwServiceRegister

NewRestLogMwServiceRegister will generate a new registry instance

func (RestLogMwServiceRegister) Provide added in v0.3.0

func (RestLogMwServiceRegister) Provide(
	container *slate.ServiceContainer,
) error

Provide will add to the container a new file system adapter instance.

type RestMiddleware

type RestMiddleware func(gin.HandlerFunc) gin.HandlerFunc

RestMiddleware defines a type of data that represents a rest method middleware function.

type RestProcess

type RestProcess struct {
	slate.WatchdogProcess
}

RestProcess defines the REST watchdog process instance.

func NewRestProcess

func NewRestProcess(
	config *slate.Config,
	logger *slate.Log,
	engine RestEngine,
) (*RestProcess, error)

NewRestProcess will try to instantiate an REST watchdog process.

type RestServiceRegister

type RestServiceRegister struct {
	slate.ServiceRegister
}

RestServiceRegister defines the REST services provider instance.

func NewRestServiceRegister added in v0.1.1

func NewRestServiceRegister(
	app ...*slate.App,
) *RestServiceRegister

NewRestServiceRegister will generate a new registry instance

func (RestServiceRegister) Boot

func (sr RestServiceRegister) Boot(
	container *slate.ServiceContainer,
) (e error)

Boot will start the REST engine with the defined controllers.

func (RestServiceRegister) Provide

func (sr RestServiceRegister) Provide(
	container *slate.ServiceContainer,
) error

Provide will register the REST section instances in the application container.

type ValidationParser

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

ValidationParser @todo doc

func NewValidationParser

func NewValidationParser(
	translator ut.Translator,
) (*ValidationParser, error)

NewValidationParser instantiate a new validation parser instance

func (*ValidationParser) AddError

func (p *ValidationParser) AddError(
	e string,
	code int,
)

AddError will add a validation mapped error to code value.

func (*ValidationParser) Parse

func (p *ValidationParser) Parse(
	val interface{},
	errs validator.ValidationErrors,
) (*Envelope, error)

Parse method that will convert the list of validation error into an envelope struct to be used as the endpoint response.

type ValidationServiceRegister

type ValidationServiceRegister struct {
	slate.ServiceRegister
}

ValidationServiceRegister @todo doc

func NewValidationServiceRegister

func NewValidationServiceRegister(
	app ...*slate.App,
) *ValidationServiceRegister

NewValidationServiceRegister will generate a new registry instance

func (ValidationServiceRegister) Provide

func (sr ValidationServiceRegister) Provide(
	container *slate.ServiceContainer,
) error

Provide will register the validation package instances in the application container

type Validator

type Validator func(val interface{}) (*Envelope, error)

Validator is a function type used to define a calling interface of function responsible to validate an instance of a structure and return an initialized response envelope with the founded error

func NewValidator

func NewValidator(
	translator ut.Translator,
	parser *ValidationParser,
) (Validator, error)

NewValidator instantiates a new validation function

Jump to

Keyboard shortcuts

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