services

package
v1.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2023 License: MIT Imports: 29 Imported by: 14

Documentation

Index

Constants

This section is empty.

Variables

View Source
var HttpRequestDetector = THttpRequestDetector{}

HttpRequestDetector рelper class that retrieves parameters from HTTP requests.

Functions

This section is empty.

Types

type AboutOperations

type AboutOperations struct {
	RestOperations
	// contains filtered or unexported fields
}

func (*AboutOperations) About

func (c *AboutOperations) About(res http.ResponseWriter, req *http.Request)

func (*AboutOperations) GetAboutOperation

func (c *AboutOperations) GetAboutOperation() func(res http.ResponseWriter, req *http.Request)

func (*AboutOperations) GetNetworkAddresses

func (c *AboutOperations) GetNetworkAddresses() []string

func (*AboutOperations) SetReferences

func (c *AboutOperations) SetReferences(references crefer.IReferences)

type CommandableHttpService

type CommandableHttpService struct {
	*RestService

	SwaggerAuto bool
	// contains filtered or unexported fields
}

CommandableHttpService abstract service that receives remove calls via HTTP/REST protocol to operations automatically generated for commands defined in ICommandable components. Each command is exposed as POST operation that receives all parameters in body object.

Commandable services require only 3 lines of code to implement a robust external HTTP-based remote interface.

Configuration parameters:

  • base_route: base route for remote URI
  • dependencies:
  • endpoint: override for HTTP Endpoint dependency
  • controller: override for Controller dependency
  • connection(s):
  • discovery_key: (optional) a key to retrieve the connection from IDiscovery
  • protocol: connection protocol: http or https
  • host: host name or IP address
  • port: port number
  • uri: resource URI or connection string with all parameters in it

References:

- *:logger:*:*:1.0 (optional) ILogger components to pass log messages - *:counters:*:*:1.0 (optional) ICounters components to pass collected measurements - *:discovery:*:*:1.0 (optional) IDiscovery services to resolve connection - *:endpoint:http:*:1.0 (optional) HttpEndpoint reference

See CommandableHttpClient See RestService

Example:

	type MyCommandableHttpService struct {
	 *CommandableHttpService
	}

	func NewMyCommandableHttpService() *MyCommandableHttpService {
		c := MyCommandableHttpService{
			CommandableHttpService: services.NewCommandableHttpService("dummies"),
		}
		c.DependencyResolver.Put("controller", cref.NewDescriptor("pip-services-dummies", "controller", "default", "*", "*"))
	return &c

    service := NewMyCommandableHttpService();
    service.Configure(cconf.NewConfigParamsFromTuples(
        "connection.protocol", "http",
        "connection.host", "localhost",
        "connection.port", 8080,
    ));
    service.SetReferences(cref.NewReferencesFromTuples(
       cref.NewDescriptor("mygroup","controller","default","default","1.0"), controller
    ));

	opnErr:=service.Open("123")
	if opnErr == nil {
       fmt.Println("The REST service is running on port 8080");
	}

func InheritCommandableHttpService added in v1.1.4

func InheritCommandableHttpService(overrides IRestServiceOverrides, baseRoute string) *CommandableHttpService

InheritCommandableHttpService creates a new instance of the service. Parameters:

  • overrides references to child class that overrides virtual methods
  • baseRoute string a service base route.

Returns: *CommandableHttpService pointer on new instance CommandableHttpService

func (*CommandableHttpService) Configure added in v1.0.7

func (c *CommandableHttpService) Configure(config *cconf.ConfigParams)

Configure method configures component by passing configuration parameters.

  • config configuration parameters to be set.

func (*CommandableHttpService) Register

func (c *CommandableHttpService) Register()

Register method are registers all service routes in HTTP endpoint.

type CommandableSwaggerDocument added in v1.0.7

type CommandableSwaggerDocument struct {
	Commands []ccomands.ICommand

	Version   string
	BaseRoute string

	InfoTitle          string
	InfoDescription    string
	InfoVersion        string
	InfoTermsOfService string

	InfoContactName  string
	InfoContactUrl   string
	InfoContactEmail string

	InfoLicenseName string
	InfoLicenseUrl  string
	// contains filtered or unexported fields
}

func NewCommandableSwaggerDocument added in v1.0.7

func NewCommandableSwaggerDocument(baseRoute string, config *cconf.ConfigParams, commands []ccomands.ICommand) *CommandableSwaggerDocument

func (*CommandableSwaggerDocument) GetSpaces added in v1.0.7

func (c *CommandableSwaggerDocument) GetSpaces(length int) string

func (*CommandableSwaggerDocument) ToString added in v1.0.7

func (c *CommandableSwaggerDocument) ToString() string

func (*CommandableSwaggerDocument) WriteData added in v1.0.7

func (c *CommandableSwaggerDocument) WriteData(indent int, data map[string]interface{})

func (*CommandableSwaggerDocument) WriteName added in v1.0.7

func (c *CommandableSwaggerDocument) WriteName(indent int, name string)

type HeartbeatOperations

type HeartbeatOperations struct {
	RestOperations
}

func NewHeartbeatOperations

func NewHeartbeatOperations() *HeartbeatOperations

NewHeartbeatOperations creates new instance HeartbeatOperations Returns: *HeartbeatOperations

func (*HeartbeatOperations) GetHeartbeatOperation

func (c *HeartbeatOperations) GetHeartbeatOperation() func(res http.ResponseWriter, req *http.Request)

Heartbeat method are insert timestamp into HTTP result

func (*HeartbeatOperations) Heartbeat

func (c *HeartbeatOperations) Heartbeat(res http.ResponseWriter, req *http.Request)

Heartbeat method are insert timestamp into HTTP result

type HeartbeatRestService

type HeartbeatRestService struct {
	*RestService
	// contains filtered or unexported fields
}

HeartbeatRestService service returns heartbeat via HTTP/REST protocol.

The service responds on /heartbeat route (can be changed) with a string with the current time in UTC.

This service route can be used to health checks by loadbalancers and container orchestrators.

Configuration parameters:

  • baseroute: base route for remote URI (default: "")
  • route: route to heartbeat operation (default: "heartbeat")
  • dependencies:
  • endpoint: override for HTTP Endpoint dependency
  • connection(s):
  • discovery_key: (optional) a key to retrieve the connection from IDiscovery
  • protocol: connection protocol: http or https
  • host: host name or IP address
  • port: port number
  • uri: resource URI or connection string with all parameters in it

References:

- *:logger:*:*:1.0 (optional) ILogger components to pass log messages - *:counters:*:*:1.0 (optional) ICounters components to pass collected measurements - *:discovery:*:*:1.0 (optional) IDiscovery services to resolve connection - *:endpoint:http:*:1.0 (optional) HttpEndpoint reference

See RestService See RestClient

Example:

service := NewHeartbeatService();
service.Configure(cconf.NewConfigParamsFromTuples(
    "route", "ping",
    "connection.protocol", "http",
    "connection.host", "localhost",
    "connection.port", 8080,
));

opnErr := service.Open("123")
if opnErr == nil {
   fmt.Println("The Heartbeat service is accessible at http://+:8080/ping");
}

func NewHeartbeatRestService

func NewHeartbeatRestService() *HeartbeatRestService

*

Creates a new instance of c service.

func (*HeartbeatRestService) Configure

func (c *HeartbeatRestService) Configure(config *cconf.ConfigParams)

*

Configures component by passing configuration parameters.

@param config    configuration parameters to be set.

func (*HeartbeatRestService) Register

func (c *HeartbeatRestService) Register()

*

Registers all service routes in HTTP endpoint.

type HttpEndpoint

type HttpEndpoint struct {
	ITlsConfigurator
	// contains filtered or unexported fields
}
HttpEndpoint used for creating HTTP endpoints. An endpoint is a URL, at which a given service can be accessed by a client.

Configuration parameters:

Parameters to pass to the configure method for component configuration:

  • cors_headers - a comma-separated list of allowed CORS headers
  • cors_origins - a comma-separated list of allowed CORS origins
  • connection(s) - the connection resolver"s connections:
  • "connection.discovery_key" - the key to use for connection resolving in a discovery service;
  • "connection.protocol" - the connection"s protocol;
  • "connection.host" - the target host;
  • "connection.port" - the target port;
  • "connection.uri" - the target URI.
  • credential - the HTTPS credentials:
  • "credential.ssl_key_file" - the SSL func (c *HttpEndpoint )key in PEM
  • "credential.ssl_crt_file" - the SSL certificate in PEM
  • "credential.ssl_ca_file" - the certificate authorities (root cerfiticates) in PEM
  • options - the http endpoint options
  • "options.client_auth_type" - authentification type (request_client_cert, require_any_client_cert, verify_client_cert_if_given, require_and_verify_client_cert, default: no_client_auth)
  • "options.certificate_server_name" - certificates server (default: letsencrypt.org) References:

A logger, counters, and a connection resolver can be referenced by passing the following references to the object"s setReferences method:

  • logger: "*:logger:*:*:1.0";
  • counters: "*:counters:*:*:1.0";
  • discovery: "*:discovery:*:*:1.0" (for the connection resolver).

Examples:

    endpoint := NewHttpEndpoint();
    endpoint.Configure(config);
    endpoint.SetReferences(references);
    ...
	endpoint.Open(correlationId)

func InheritTlsHttpEndpoint added in v1.6.0

func InheritTlsHttpEndpoint(configurator ITlsConfigurator) *HttpEndpoint

NewHttpEndpoint inherit configurator

func NewHttpEndpoint

func NewHttpEndpoint() *HttpEndpoint

NewHttpEndpoint creates new HttpEndpoint

func (*HttpEndpoint) AddCorsHeader added in v1.4.0

func (c *HttpEndpoint) AddCorsHeader(header string, origin string)

AddCORSHeader method adds allowed header, ignore if it already exist must be call before to opening endpoint

func (*HttpEndpoint) Close

func (c *HttpEndpoint) Close(correlationId string) error

Close method are closes this endpoint and the REST server (service) that was opened earlier. Parameters:

  • correlationId string (optional) transaction id to trace execution through call chain.

Returns: error an error if one is raised.

func (*HttpEndpoint) Configure

func (c *HttpEndpoint) Configure(config *cconf.ConfigParams)

Configure method are configures this HttpEndpoint using the given configuration parameters. Configuration parameters:

  • connection(s) - the connection resolver"s connections;
  • "connection.discovery_key" - the key to use for connection resolving in a discovery service;
  • "connection.protocol" - the connection"s protocol;
  • "connection.host" - the target host;
  • "connection.port" - the target port;
  • "connection.uri" - the target URI.
  • "credential.ssl_key_file" - SSL func (c *HttpEndpoint )key in PEM
  • "credential.ssl_crt_file" - SSL certificate in PEM
  • "credential.ssl_ca_file" - Certificate authority (root certificate) in PEM
  • config configuration parameters, containing a "connection(s)" section.

func (*HttpEndpoint) GetCaCert added in v1.6.0

func (c *HttpEndpoint) GetCaCert() (*x509.CertPool, error)

func (*HttpEndpoint) GetCertificates added in v1.6.0

func (c *HttpEndpoint) GetCertificates() ([]tls.Certificate, error)

func (*HttpEndpoint) GetClientAuthType added in v1.6.0

func (c *HttpEndpoint) GetClientAuthType() tls.ClientAuthType

func (*HttpEndpoint) GetCorrelationId added in v1.0.14

func (c *HttpEndpoint) GetCorrelationId(req *http.Request) string

GetCorrelationId method returns CorrelationId from request Parameters:

req *http.Request  request

Returns: string retrun correlation_id or empty string

func (*HttpEndpoint) IsOpen

func (c *HttpEndpoint) IsOpen() bool

IsOpen method is whether or not this endpoint is open with an actively listening REST server.

func (*HttpEndpoint) Open

func (c *HttpEndpoint) Open(correlationId string) error

Opens a connection using the parameters resolved by the referenced connection resolver and creates a REST server (service) using the set options and parameters. Parameters:

  • correlationId string (optional) transaction id to trace execution through call chain.

Returns : error an error if one is raised.

func (*HttpEndpoint) Register

func (c *HttpEndpoint) Register(registration IRegisterable)

Registers a registerable object for dynamic endpoint discovery. Parameters:

  • registration IRegisterable implements of IRegisterable interface.

See IRegisterable

func (*HttpEndpoint) RegisterInterceptor

func (c *HttpEndpoint) RegisterInterceptor(route string, action func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc))

RegisterInterceptor method are registers a middleware action for the given route.

  • route the route to register in this object"s REST server (service).
  • action the middleware action to perform at the given route.

func (*HttpEndpoint) RegisterRoute

func (c *HttpEndpoint) RegisterRoute(method string, route string, schema *cvalid.Schema,
	action http.HandlerFunc)

RegisterRoute method are registers an action in this objects REST server (service) by the given method and route.

  • method string the HTTP method of the route.
  • route string the route to register in this object"s REST server (service).
  • schema *cvalid.Schema the schema to use for parameter validation.
  • action http.HandlerFunc the action to perform at the given route.

func (*HttpEndpoint) RegisterRouteWithAuth

func (c *HttpEndpoint) RegisterRouteWithAuth(method string, route string, schema *cvalid.Schema,
	authorize func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc),
	action http.HandlerFunc)

RegisterRouteWithAuth method are registers an action with authorization in this objects REST server (service) by the given method and route. Parameters:

  • method string the HTTP method of the route.
  • route string the route to register in this object"s REST server (service).
  • schema *cvalid.Schema the schema to use for parameter validation.
  • authorize the authorization interceptor
  • action the action to perform at the given route.

func (*HttpEndpoint) SetReferences

func (c *HttpEndpoint) SetReferences(references crefer.IReferences)

SetReferences method are sets references to this endpoint"s logger, counters, and connection resolver.

References:
- logger: "*:logger:*:*:1.0"
- counters: "*:counters:*:*:1.0"
- discovery: "*:discovery:*:*:1.0" (for the connection resolver)

Parameters:

  • references an IReferences object, containing references to a logger, counters, and a connection resolver.

func (*HttpEndpoint) Unregister

func (c *HttpEndpoint) Unregister(registration IRegisterable)

Unregisters a registerable object, so that it is no longer used in dynamic endpoint discovery. Parameters:

  • registration IRegisterable the registration to remove.

See IRegisterable

type IRegisterable

type IRegisterable interface {
	// Perform required registration steps.
	Register()
}

IRegisterable is interface to perform on-demand registrations.

type IRestServiceOverrides added in v1.1.4

type IRestServiceOverrides interface {
	Register()
}

type ISwaggerService added in v1.0.7

type ISwaggerService interface {

	//  Perform required Swagger registration steps.
	RegisterOpenApiSpec(baseRoute string, swaggerRoute string)
}

ISwaggerService Interface to perform Swagger registrations.

type ITlsConfigurator added in v1.6.0

type ITlsConfigurator interface {
	GetClientAuthType() tls.ClientAuthType
	GetCertificates() ([]tls.Certificate, error)
	GetCaCert() (*x509.CertPool, error)
}

type InstrumentTiming added in v1.3.1

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

func NewInstrumentTiming added in v1.3.1

func NewInstrumentTiming(correlationId string, name string,
	verb string, logger clog.ILogger, counters ccount.ICounters,
	counterTiming *ccount.CounterTiming, traceTiming *ctrace.TraceTiming) *InstrumentTiming

func (*InstrumentTiming) EndFailure added in v1.3.1

func (c *InstrumentTiming) EndFailure(err error)

func (*InstrumentTiming) EndSuccess added in v1.3.1

func (c *InstrumentTiming) EndSuccess()

func (*InstrumentTiming) EndTiming added in v1.3.1

func (c *InstrumentTiming) EndTiming(err error)

type RestOperations

type RestOperations struct {
	Logger             *clog.CompositeLogger
	Counters           *ccount.CompositeCounters
	DependencyResolver *crefer.DependencyResolver
}

RestOperations helper class for REST operations

func NewRestOperations

func NewRestOperations() *RestOperations

NewRestOperations creates new instance of RestOperations

func (*RestOperations) Configure

func (c *RestOperations) Configure(config *cconf.ConfigParams)

Configure method are configures this RestOperations using the given configuration parameters. Parameters:

  • config *cconf.ConfigParams confif parameters

func (*RestOperations) DecodeBody added in v1.0.10

func (c *RestOperations) DecodeBody(req *http.Request, target interface{}) error

DecodeBody methods helps decode body

  • req - incoming request
  • target - pointer on target variable for decode

Returns error

func (*RestOperations) GetCorrelationId

func (c *RestOperations) GetCorrelationId(req *http.Request) string

GetCorrelationId method returns CorrelationId from request Parameters:

req *http.Request  request

Returns: string retrun correlation_id or empty string

func (*RestOperations) GetFilterParams

func (c *RestOperations) GetFilterParams(req *http.Request) *cdata.FilterParams

GetFilterParams method retruns filter params object from request Parameters:

req *http.Request  request

Returns: *cdata.FilterParams filter params object

func (*RestOperations) GetPagingParams

func (c *RestOperations) GetPagingParams(req *http.Request) *cdata.PagingParams

GetPagingParams method retruns paging params object from request Parameters:

req *http.Request  request

Returns: *cdata.PagingParams pagings params object

func (*RestOperations) GetParam added in v1.0.10

func (c *RestOperations) GetParam(req *http.Request, name string) string

GetParam methods helps get all params from query

  • req - incoming request
  • name - parameter name

Returns value or empty string if param not exists

func (*RestOperations) SendBadRequest

func (c *RestOperations) SendBadRequest(res http.ResponseWriter, req *http.Request, message string)

func (*RestOperations) SendConflict

func (c *RestOperations) SendConflict(res http.ResponseWriter, req *http.Request, message string)

func (*RestOperations) SendCreatedResult

func (c *RestOperations) SendCreatedResult(res http.ResponseWriter, req *http.Request, result interface{}, err error)

func (*RestOperations) SendDeletedResult

func (c *RestOperations) SendDeletedResult(res http.ResponseWriter, req *http.Request, result interface{}, err error)

func (*RestOperations) SendEmptyResult

func (c *RestOperations) SendEmptyResult(res http.ResponseWriter, req *http.Request, err error)

func (*RestOperations) SendError

func (c *RestOperations) SendError(res http.ResponseWriter, req *http.Request, err error)

func (*RestOperations) SendInternalError

func (c *RestOperations) SendInternalError(res http.ResponseWriter, req *http.Request, message string)

func (*RestOperations) SendNotFound

func (c *RestOperations) SendNotFound(res http.ResponseWriter, req *http.Request, message string)

func (*RestOperations) SendResult

func (c *RestOperations) SendResult(res http.ResponseWriter, req *http.Request, result interface{}, err error)

func (*RestOperations) SendServerUnavailable

func (c *RestOperations) SendServerUnavailable(res http.ResponseWriter, req *http.Request, message string)

func (*RestOperations) SendSessionExpired

func (c *RestOperations) SendSessionExpired(res http.ResponseWriter, req *http.Request, message string)

func (*RestOperations) SendUnauthorized

func (c *RestOperations) SendUnauthorized(res http.ResponseWriter, req *http.Request, message string)

func (*RestOperations) SetReferences

func (c *RestOperations) SetReferences(references crefer.IReferences)

SetReferences method are sets references to this RestOperations logger, counters, and connection resolver. Parameters:

  • references an IReferences object, containing references to a logger, counters, and a dependency resolver.

type RestService

type RestService struct {
	Overrides IRestServiceOverrides

	//The base route.
	BaseRoute string
	//The HTTP endpoint that exposes this service.
	Endpoint *HttpEndpoint
	//The dependency resolver.
	DependencyResolver *crefer.DependencyResolver
	//The logger.
	Logger *clog.CompositeLogger
	//The performance counters.
	Counters *ccount.CompositeCounters
	// The tracer.
	Tracer *ctrace.CompositeTracer

	SwaggerService ISwaggerService
	SwaggerEnabled bool
	SwaggerRoute   string
	// contains filtered or unexported fields
}

RestService Abstract service that receives remove calls via HTTP/REST protocol.

Configuration parameters:

  • base_route: base route for remote URI
  • dependencies:
  • endpoint: override for HTTP Endpoint dependency
  • controller: override for Controller dependency
  • connection(s):
  • discovery_key: (optional) a key to retrieve the connection from IDiscovery
  • protocol: connection protocol: http or https
  • host: host name or IP address
  • port: port number
  • uri: resource URI or connection string with all parameters in it
  • credential - the HTTPS credentials:
  • ssl_key_file: the SSL private key in PEM
  • ssl_crt_file: the SSL certificate in PEM
  • ssl_ca_file: the certificate authorities (root cerfiticates) in PEM

References:

- *:logger:*:*:1.0 (optional) ILogger components to pass log messages - *:counters:*:*:1.0 (optional) ICounters components to pass collected measurements - *:discovery:*:*:1.0 (optional) IDiscovery services to resolve connection - *:endpoint:http:*:1.0 (optional) HttpEndpoint reference

See RestClient

Example:

    type MyRestService struct {
		*RestService
		controller IMyController
	}

	   ...
	func NewMyRestService() *MyRestService {
		c := MyRestService{}
		c.RestService = services.NewRestService()
		c.RestService.IRegisterable = &c
		c.numberOfCalls = 0
		c.DependencyResolver.Put("controller", crefer.NewDescriptor("mygroup", "controller", "*", "*", "1.0"))
		return &c
	}

    func (c * MyRestService) SetReferences(references IReferences) {
        c.RestService.SetReferences(references);
		resolv := c.DependencyResolver.GetRequired("controller");
		if resolv != nil {
			c.controller, _ = resolv.(IMyController)
		}
    }

	func (c *MyRestService) getOneById(res http.ResponseWriter, req *http.Request) {
		params := req.URL.Query()
		vars := mux.Vars(req)

		mydataId := params.Get("mydata_id")
		if mydataId == "" {
			mydataId = vars["mydatay_id"]
		}
		result, err := c.controller.GetOneById(
			params.Get("correlation_id"),
			mydataId)
		c.SendResult(res, req, result, err)

	}
    func (c * MyRestService) Register() {

		c.RegisterRoute(
		"get", "get_mydata/{mydata_id}",
		 &cvalid.NewObjectSchema().
			WithRequiredProperty("mydata_id", cconv.String).Schema,
		c.getOneById)
           ...
    }

    service := NewMyRestService();
    service.Configure(cconf.NewConfigParamsFromTuples(
        "connection.protocol", "http",
        "connection.host", "localhost",
        "connection.port", 8080,
    ));
    service.SetReferences(cref.NewReferencesFromTuples(
       cref.NewDescriptor("mygroup","controller","default","default","1.0"), controller
    ));

	opnRes := service.Open("123")
	if opnErr == nil {
	   fmt.Println("The REST service is running on port 8080");
	}

func InheritRestService added in v1.1.4

func InheritRestService(overrides IRestServiceOverrides) *RestService

InheritRestService is create new instance of RestService

func (*RestService) Close

func (c *RestService) Close(correlationId string) error

Close method are closes component and frees used resources. Parameters:

  • correlationId (optional) transaction id to trace execution through call chain.

Returns: error error or nil no errors occured.

func (*RestService) Configure

func (c *RestService) Configure(config *cconf.ConfigParams)

Configure method are configures component by passing configuration parameters. Parameters:

  • config *cconf.ConfigParams configuration parameters to be set.

func (*RestService) DecodeBody added in v1.0.4

func (c *RestService) DecodeBody(req *http.Request, target interface{}) error

DecodeBody methods helps decode body

  • req - incoming request
  • target - pointer on target variable for decode

Returns error

func (*RestService) GetCorrelationId added in v1.0.14

func (c *RestService) GetCorrelationId(req *http.Request) string

GetCorrelationId method returns CorrelationId from request Parameters:

req *http.Request  request

Returns: string retrun correlation_id or empty string

func (*RestService) GetFilterParams added in v1.0.6

func (c *RestService) GetFilterParams(req *http.Request) *cdata.FilterParams

GetFilterParams methods helps decode filter params

  • req - incoming request

Returns filter params

func (*RestService) GetPagingParams added in v1.0.6

func (c *RestService) GetPagingParams(req *http.Request) *cdata.PagingParams

GetPagingParams methods helps decode paging params

  • req - incoming request

Returns paging params

func (*RestService) GetParam added in v1.0.4

func (c *RestService) GetParam(req *http.Request, name string) string

GetParam methods helps get all params from query

  • req - incoming request
  • name - parameter name

Returns value or empty string if param not exists

func (*RestService) Instrument

func (c *RestService) Instrument(correlationId string, name string) *InstrumentTiming

Instrument method are adds instrumentation to log calls and measure call time. It returns a Timing object that is used to end the time measurement. Parameters:

  • correlationId (optional) transaction id to trace execution through call chain.
  • name a method name.

Returns Timing object to end the time measurement.

func (*RestService) InstrumentError

func (c *RestService) InstrumentError(correlationId string, name string, errIn error,
	resIn interface{}) (result interface{}, err error)

InstrumentError method are adds instrumentation to error handling. Parameters:

  • correlationId string (optional) transaction id to trace execution through call chain.
  • name string a method name.
  • err error an occured error
  • result interface{} (optional) an execution result

Returns: result interface{}, err error

(optional) an execution callback

func (*RestService) IsOpen

func (c *RestService) IsOpen() bool

IsOpen method checks if the component is opened. Returrns true if the component has been opened and false otherwise.

func (*RestService) Open

func (c *RestService) Open(correlationId string) error

Open method are opens the component. Parameters:

  • correlationId string: (optional) transaction id to trace execution through call chain. Returns: error

error or nil no errors occured.

func (*RestService) Register added in v1.1.4

func (c *RestService) Register()

Register method are registers all service routes in HTTP endpoint.

func (*RestService) RegisterInterceptor

func (c *RestService) RegisterInterceptor(route string,
	action func(res http.ResponseWriter, req *http.Request, next http.HandlerFunc))

RegisterInterceptor method are registers a middleware for a given route in HTTP endpoint. Parameters:

  • route a command route. Base route will be added to this route
  • action an action function that is called when middleware is invoked.

func (*RestService) RegisterOpenApiSpec added in v1.0.7

func (c *RestService) RegisterOpenApiSpec(content string)

func (*RestService) RegisterOpenApiSpecFromFile added in v1.0.7

func (c *RestService) RegisterOpenApiSpecFromFile(path string)

func (*RestService) RegisterRoute

func (c *RestService) RegisterRoute(method string, route string, schema *cvalid.Schema,
	action func(res http.ResponseWriter, req *http.Request))

RegisterRoute method are registers a route in HTTP endpoint. Parameters:

  • method HTTP method: "get", "head", "post", "put", "delete"
  • route a command route. Base route will be added to this route
  • schema a validation schema to validate received parameters.
  • action an action function that is called when operation is invoked.

func (*RestService) RegisterRouteWithAuth

func (c *RestService) RegisterRouteWithAuth(method string, route string, schema *cvalid.Schema,
	authorize func(res http.ResponseWriter, req *http.Request, next http.HandlerFunc),
	action func(res http.ResponseWriter, req *http.Request))

RegisterRouteWithAuth method are registers a route with authorization in HTTP endpoint. Parameters:

  • method HTTP method: "get", "head", "post", "put", "delete"
  • route a command route. Base route will be added to this route
  • schema a validation schema to validate received parameters.
  • authorize an authorization interceptor
  • action an action function that is called when operation is invoked.

func (*RestService) SendCreatedResult

func (c *RestService) SendCreatedResult(res http.ResponseWriter, req *http.Request, result interface{}, err error)

SendCreatedResult method are sends newly created object as JSON. That callack function call be called directly or passed as a parameter to business logic components. If object is not nil it returns 201 status code. For nil results it returns 204 status code. If error occur it sends ErrorDescription with approproate status code. Parameters:

  • req a HTTP request object.
  • res a HTTP response object.
  • result (optional) result object to send
  • err error (optional) error objrct to send

func (*RestService) SendDeletedResult

func (c *RestService) SendDeletedResult(res http.ResponseWriter, req *http.Request, result interface{}, err error)

SendDeletedResult method are sends deleted object as JSON. That callack function call be called directly or passed as a parameter to business logic components. If object is not nil it returns 200 status code. For nil results it returns 204 status code. If error occur it sends ErrorDescription with approproate status code. Parameters:

  • req a HTTP request object.
  • res a HTTP response object.
  • result (optional) result object to send
  • err error (optional) error objrct to send

func (*RestService) SendError

func (c *RestService) SendError(res http.ResponseWriter, req *http.Request, err error)

SendError method are sends error serialized as ErrorDescription object and appropriate HTTP status code. If status code is not defined, it uses 500 status code. Parameters:

  • req a HTTP request object.
  • res a HTTP response object.
  • error an error object to be sent.

func (*RestService) SendResult

func (c *RestService) SendResult(res http.ResponseWriter, req *http.Request, result interface{}, err error)

SendResult method method are sends result as JSON object. That function call be called directly or passed as a parameter to business logic components. If object is not nil it returns 200 status code. For nil results it returns 204 status code. If error occur it sends ErrorDescription with approproate status code. Parameters:

  • req a HTTP request object.
  • res a HTTP response object.
  • result (optional) result object to send
  • err error (optional) error objrct to send

func (*RestService) SetReferences

func (c *RestService) SetReferences(references crefer.IReferences)

SetReferences method are sets references to dependent components. Parameters:

  • references crefer.IReferences references to locate the component dependencies.

func (*RestService) UnsetReferences

func (c *RestService) UnsetReferences()

UnsetReferences method are unsets (clears) previously set references to dependent components.

type StatusOperations

type StatusOperations struct {
	RestOperations
	// contains filtered or unexported fields
}

StatusOperations helper class for status service

func NewStatusOperations

func NewStatusOperations() *StatusOperations

NewStatusOperations creates new instance of StatusOperations

func (*StatusOperations) GetStatusOperation

func (c *StatusOperations) GetStatusOperation() func(res http.ResponseWriter, req *http.Request)

GetStatusOperation return function for get status

func (*StatusOperations) SetReferences

func (c *StatusOperations) SetReferences(references crefer.IReferences)

SetReferences sets references to dependent components.

  • references crefer.IReferences references to locate the component dependencies.

func (*StatusOperations) Status

func (c *StatusOperations) Status(res http.ResponseWriter, req *http.Request)

Status method handles status requests

  • req *http.Request an HTTP request
  • res http.ResponseWriter an HTTP response

type StatusRestService

type StatusRestService struct {
	*RestService
	// contains filtered or unexported fields
}

StatusRestService is a service that returns microservice status information via HTTP/REST protocol.

The service responds on /status route (can be changed) with a JSON object:

{
  - "id":            unique container id (usually hostname)
  - "name":          container name (from ContextInfo)
  - "description":   container description (from ContextInfo)
  - "start_time":    time when container was started
  - "current_time":  current time in UTC
  - "uptime":        duration since container start time in milliseconds
  - "properties":    additional container properties (from ContextInfo)
  - "components":    descriptors of components registered in the container
}

Configuration parameters:

  • baseroute: base route for remote URI
  • route: status route (default: "status")
  • dependencies:
  • endpoint: override for HTTP Endpoint dependency
  • controller: override for Controller dependency
  • connection(s):
  • discovery_key: (optional) a key to retrieve the connection from IDiscovery
  • protocol: connection protocol: http or https
  • host: host name or IP address
  • port: port number
  • uri: resource URI or connection string with all parameters in it

References:

- *:logger:*:*:1.0 (optional) ILogger components to pass log messages - *:counters:*:*:1.0 (optional) ICounters components to pass collected measurements - *:discovery:*:*:1.0 (optional) IDiscovery services to resolve connection - *:endpoint:http:*:1.0 (optional) HttpEndpoint reference

See: RestService See: RestClient

Example:

    service = NewStatusService();
    service.Configure(cref.NewConfigParamsFromTuples(
        "connection.protocol", "http",
        "connection.host", "localhost",
        "connection.port", 8080,
    ));

	opnErr:= service.Open("123")
	if opnErr == nil {
       fmt.Println("The Status service is accessible at http://localhost:8080/status");
    }

func NewStatusRestService

func NewStatusRestService() *StatusRestService

NewStatusRestService method are creates a new instance of this service.

func (*StatusRestService) Configure

func (c *StatusRestService) Configure(config *cconf.ConfigParams)

Configure method are configures component by passing configuration parameters. Parameters:

  • config *cconf.ConfigParams configuration parameters to be set.

func (*StatusRestService) Register

func (c *StatusRestService) Register()

Register method are registers all service routes in HTTP endpoint.

func (*StatusRestService) SetReferences

func (c *StatusRestService) SetReferences(references crefer.IReferences)

SetReferences method are sets references to dependent components. Parameters:

  • references crefer.IReferences references to locate the component dependencies.

type THttpRequestDetector

type THttpRequestDetector struct {
}

func (*THttpRequestDetector) DetectAddress

func (c *THttpRequestDetector) DetectAddress(req *http.Request) string

DetectAddress method are detects the IP address from which the given HTTP request was received.

  • req *http.Reques an HTTP request to process. Returns the detected IP address (without a port). If no IP is detected -

nil will be returned.

func (*THttpRequestDetector) DetectBrowser

func (c *THttpRequestDetector) DetectBrowser(req *http.Request) string

Detects the browser (using "user-agent") from which the given HTTP request was made.

  • req *http.Reques an HTTP request to process. Returns the detected browser. Detectable browsers: "chrome", "msie", "firefox",

"safari". Otherwise - "unknown" will be returned.

func (*THttpRequestDetector) DetectPlatform

func (c *THttpRequestDetector) DetectPlatform(req *http.Request) string

DetectPlatform method are detects the platform (using "user-agent") from which the given HTTP request was made.

  • req *http.Request an HTTP request to process. Returns the detected platform and version. Detectable platforms: "mobile", "iphone", "ipad", "macosx", "android", "webos", "mac", "windows". Otherwise - "unknown" will

be returned.

func (*THttpRequestDetector) DetectServerHost

func (c *THttpRequestDetector) DetectServerHost(req *http.Request) string

DetectServerHost method are detects the host name of the request"s destination server.

  • req *http.Request an HTTP request to process. Returns the destination server"s host name.

func (*THttpRequestDetector) DetectServerPort

func (c *THttpRequestDetector) DetectServerPort(req *http.Request) string

DetectServerPort method are detects the request"s destination port number.

  • req *http.Request an HTTP request to process. Returns the detected port number or <code>80</code> (if none are detected).

type THttpResponseSender

type THttpResponseSender struct {
}
var HttpResponseSender THttpResponseSender = THttpResponseSender{}

func (*THttpResponseSender) SendCreatedResult

func (c *THttpResponseSender) SendCreatedResult(res http.ResponseWriter, req *http.Request, result interface{}, err error)

SendCreatedResult are sends newly created object as JSON. That function call be called directly or passed as a parameter to business logic components. If object is not nil it returns 201 status code. For nil results it returns 204 status code. If error occur it sends ErrorDescription with approproate status code. Parameters:

  • req *http.Request a HTTP request object.
  • res http.ResponseWriter a HTTP response object.

func (*THttpResponseSender) SendDeletedResult

func (c *THttpResponseSender) SendDeletedResult(res http.ResponseWriter, req *http.Request, result interface{}, err error)

SendDeletedResult are sends deleted object as JSON. That function call be called directly or passed as a parameter to business logic components. If object is not nil it returns 200 status code. For nil results it returns 204 status code. If error occur it sends ErrorDescription with approproate status code. Parameters:

  • req *http.Request a HTTP request object.
  • res http.ResponseWriter a HTTP response object.

func (*THttpResponseSender) SendEmptyResult

func (c *THttpResponseSender) SendEmptyResult(res http.ResponseWriter, req *http.Request, err error)

SendEmptyResult are sends an empty result with 204 status code. If error occur it sends ErrorDescription with approproate status code.

  • req *http.Request a HTTP request object.
  • res http.ResponseWriter a HTTP response object.

func (*THttpResponseSender) SendError

func (c *THttpResponseSender) SendError(res http.ResponseWriter, req *http.Request, err error)

SendError sends error serialized as ErrorDescription object and appropriate HTTP status code. If status code is not defined, it uses 500 status code. Parameters:

  • req *http.Request a HTTP request object.
  • res http.ResponseWriter a HTTP response object.
  • err error an error object to be sent.

func (*THttpResponseSender) SendResult

func (c *THttpResponseSender) SendResult(res http.ResponseWriter, req *http.Request, result interface{}, err error)

SendResult sends result as JSON object. That function call be called directly or passed as a parameter to business logic components. If object is not nil it returns 200 status code. For nil results it returns 204 status code. If error occur it sends ErrorDescription with approproate status code. Parameters:

  • req *http.Request a HTTP request object.
  • res http.ResponseWriter a HTTP response object.
  • result interface{} result object to be send
  • err error an error object to be sent.

Jump to

Keyboard shortcuts

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