goserv

package module
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Apr 7, 2020 License: Apache-2.0 Imports: 20 Imported by: 0

README

goserv

A library that provides support for creating microservices.

Overview

Installation

Make sure you have a working Go environment. The core library has an external dependency on go-restful. To run the unit tests, however, the testify library is required.

To install, run:

go get github.com/dakiva/goserv

About

This library is written by Daniel Akiva (dakiva) and is licensed under the apache-2.0 license. Pull requests are welcome.

Documentation

Index

Constants

View Source
const (
	// DefaultMaxOpenConnections represents the default number of open database connections
	DefaultMaxOpenConnections = 10
	// DefaultMaxIdleConnections represents the default number of idle database connections
	DefaultMaxIdleConnections = 10
)
View Source
const (
	// DefaultRequestLogFormat format
	DefaultRequestLogFormat = "[Request %s %s] trace=%s content_length=%d form=%s headers=[%s]\n"
	// DefaultResponseLogFormat format
	DefaultResponseLogFormat = "[Response %s %s] trace=%s status=%d time=%s headers=[%s]\n"

	// RequestTimestampAttribute is an attribute representing the timestamp at which the request was received by the service
	RequestTimestampAttribute = "request_timestamp_attr"
	// TraceIDAttribute is an attribute representing a unique identifier for the request useful for correlating log statements
	TraceIDAttribute = "trace_id_attr"
)

Variables

View Source
var DefaultLoggingConfig = LoggingConfig{
	LogLevel:    "DEBUG",
	LogDB:       true,
	LogEndpoint: true,
	Format:      "%{time} %{shortfile} %{level} %{message}",
	Backends: []BackendConfig{
		{
			BackendName: "STDOUT",
		},
	},
}

DefaultLoggingConfig represents a suitable logging default for development

Functions

func ConvertToFloat added in v1.4.0

func ConvertToFloat(unmarshaledVal interface{}) (float64, error)

ConvertToFloat converts a raw unmarshaled value to a float64. When unmarshaling to an interface, the unmarshaler may unmarshal a number to a json.Number or a float64. This conversion function encapsulates this behavior.

func ConvertToInteger added in v1.4.0

func ConvertToInteger(unmarshaledVal interface{}) (int, error)

ConvertToInteger converts a raw unmarshaled value to a float64. When unmarshaling to an interface, the unmarshaler may unmarshal a number to a json.Number or a float64. The float is then floored by this function and returned. This conversion function encapsulates this behavior.

func ExtractRequestBody

func ExtractRequestBody(request *restful.Request, body RequestBody) error

ExtractRequestBody extracts the body of a request into a RequestBody and validates it. Returns an error if the extraction fails.

func GetCreatedID

func GetCreatedID(rows *sqlx.Rows) (int64, error)

GetCreatedID grabs the sequential id from the result rows returned from an INSERT...RETURNING query and closes the result set.

func LoadServiceConfig

func LoadServiceConfig(fileName string, output *ServiceConfig) error

LoadServiceConfig loads configuration from a file containing configuration in JSON.

func NewDBContextProviderSQLXWrapper added in v1.2.0

func NewDBContextProviderSQLXWrapper(db *sqlx.DB, logDB bool, logger *logging.Logger) dbx.DBContextProvider

NewDBContextProviderSQLXWrapper initializes and returns a wrapped DBContextProvider instance

func WriteError

func WriteError(response *restful.Response, err error)

WriteError ensures the error is appropriately handled by ensuring the correct http status code is assigned and the error message is logged.

Types

type AccessDeniedError

type AccessDeniedError struct {
	Err error
}

AccessDeniedError represents unauthorized access to a specific system function or resource

func (*AccessDeniedError) Error

func (a *AccessDeniedError) Error() string

Error returns this error as a string

func (*AccessDeniedError) StatusCode

func (a *AccessDeniedError) StatusCode() int

StatusCode returns the HTTP status code appropriate for the error type

func (*AccessDeniedError) Unwrap

func (a *AccessDeniedError) Unwrap() error

Unwrap returns the underlying error

type BackendConfig

type BackendConfig struct {
	BackendName string `json:"backend_name"`
	FilePath    string `json:"file_path"`
}

BackendConfig represents configuration of a specific logging backend, specifically one of [STDOUT, SYSLOG, FILE]

type DBConfig

type DBConfig struct {
	Hostname           string `json:"hostname"`
	Port               int    `json:"port"`
	MaxIdleConnections int    `json:"max_idle_connections"`
	MaxOpenConnections int    `json:"max_open_connections"`
	DBName             string `json:"dbname"`
	SSLMode            string `json:"sslmode"`
	ConnectTimeout     int    `json:"connect_timeout"`
	SchemaName         string `json:"schema_name"`
	Role               string `json:"role"`
	RolePassword       string `json:"role_password"`
}

DBConfig represents database configuration that points to a specific schema and allows for connection specific settings.

func ParseDBConfig

func ParseDBConfig(dsnEnv string) (*DBConfig, error)

ParseDBConfig represents a configuration that is parsed from an environment variable. Returns an error onky if an environment variable exists and parsing data from that environment fails. If an environment variable is not set nil is returned.

func (*DBConfig) Empty

func (d *DBConfig) Empty() bool

Empty returns true if this DBConfig represents an empty configuration

func (*DBConfig) OpenDB

func (d *DBConfig) OpenDB() (*sqlx.DB, error)

OpenDB creates a pool of open connections to the database

func (*DBConfig) ToDsn

func (d *DBConfig) ToDsn() string

ToDsn converts this configuration to a standard DSN that can be used to open a connection to a specific schema.

func (*DBConfig) Validate

func (d *DBConfig) Validate() error

Validate ensures a configuration has populated all required fields.

type DBContextProviderSQLXWrapper added in v1.2.0

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

DBContextProviderSQLXWrapper wraps a sqlx DB as a content provider

func (*DBContextProviderSQLXWrapper) GetContext added in v1.2.0

func (d *DBContextProviderSQLXWrapper) GetContext() (dbx.DBContext, error)

GetContext returns a database context

func (*DBContextProviderSQLXWrapper) GetTxContext added in v1.2.0

func (d *DBContextProviderSQLXWrapper) GetTxContext() (dbx.DBTxContext, error)

GetTxContext returns a transaction context, or an error

type DuplicateResourceError

type DuplicateResourceError struct {
	ResourceTypeName string
	Err              error
}

DuplicateResourceError represents a duplicate resource signal (409) typically raised on resource creation

func (*DuplicateResourceError) Error

func (d *DuplicateResourceError) Error() string

Error returns this error as a string

func (*DuplicateResourceError) StatusCode

func (d *DuplicateResourceError) StatusCode() int

StatusCode returns the HTTP status code appropriate for the error type

func (*DuplicateResourceError) Unwrap

func (d *DuplicateResourceError) Unwrap() error

Unwrap returns the underlying error

type EndpointConfig

type EndpointConfig struct {
	Hostname string `json:"hostname"`
	Port     int    `json:"port"`
}

EndpointConfig represents the root configuration for the service

func (*EndpointConfig) GetHostAddress

func (e *EndpointConfig) GetHostAddress() string

GetHostAddress returns the host address host:port. If the host is empty, returns a leading ':'.

func (*EndpointConfig) Validate

func (e *EndpointConfig) Validate() error

Validate ensures the service config is valid

type ErrorBody

type ErrorBody struct {
	ErrorMessage string `json:"error" description:"The error message."`
	StatusCode   int    `json:"status_code" description:"The status code."`
}

ErrorBody struct is used when constructing a single error response body.

type IllegalArgumentError

type IllegalArgumentError struct {
	Argument string
	Err      error
}

IllegalArgumentError represents a bad request argument (400)

func (*IllegalArgumentError) Error

func (i *IllegalArgumentError) Error() string

Error returns this error as as string

func (*IllegalArgumentError) StatusCode

func (i *IllegalArgumentError) StatusCode() int

StatusCode returns the HTTP status code appropriate for the error type

func (*IllegalArgumentError) Unwrap

func (i *IllegalArgumentError) Unwrap() error

Unwrap returns the underlying error

type LoggingConfig

type LoggingConfig struct {
	LogLevel    string          `json:"log_level"`
	LogDB       bool            `json:"log_db"`
	LogEndpoint bool            `json:"log_endpoint"`
	Format      string          `json:"format"`
	Backends    []BackendConfig `json:"backends"`
}

LoggingConfig contains configuration for op/go-logging

func (*LoggingConfig) InitializeLogging

func (l *LoggingConfig) InitializeLogging() error

InitializeLogging configures logging based on the logging configuration.

func (*LoggingConfig) Validate

func (l *LoggingConfig) Validate() error

Validate ensures a configuration has populated all required fields.

type OAuth2ServiceConfig added in v1.6.0

type OAuth2ServiceConfig struct {
	AuthorizationURL      string `json:"authorization_url"`
	TokenURL              string `json:"token_url"`
	RedirectURL           string `json:"redirect_url"`
	AccessTokenExpiration int    `json:"access_token_expiration"`
	AccessTokenPrivateKey string `json:"access_token_private_key"`
}

OAuth2ServiceConfig represents configuration for setting up OAuth2 service flows

func (*OAuth2ServiceConfig) Validate added in v1.6.0

func (o *OAuth2ServiceConfig) Validate() error

Validate validates whether the configuration is valid for an OAuth2 service flow (redirect/grant and implicit flows supported)

type OpenIDConnectClientConfig added in v1.6.0

type OpenIDConnectClientConfig struct {
	ClientID     string `json:"client_id"`
	ClientSecret string `json:"client_secret"`
	Issuer       string `json:"issuer"`
	RedirectURL  string `json:"redirect_url"`
}

OpenIDConnectClientConfig represents configuration for setting up an OpenID Connect client

func (*OpenIDConnectClientConfig) Validate added in v1.6.0

func (o *OpenIDConnectClientConfig) Validate() error

Validate validates whether the configuration is valid for an OpenID Connect client

type RequestBody

type RequestBody interface {
	// Validate validatess the request body, returning an error if validation fails.
	Validate() error
}

RequestBody represents a request body that can be validated.

type ResourceNotFoundError

type ResourceNotFoundError struct {
	ResourceID       string
	ResourceTypeName string
	Err              error
}

ResourceNotFoundError represents an error when a resource could not be found (404).

func (*ResourceNotFoundError) Error

func (r *ResourceNotFoundError) Error() string

Error returns this error as a string

func (*ResourceNotFoundError) StatusCode

func (r *ResourceNotFoundError) StatusCode() int

StatusCode returns the HTTP status code appropriate for the error type

func (*ResourceNotFoundError) Unwrap

func (r *ResourceNotFoundError) Unwrap() error

Unwrap returns the underlying error

type ResourceResult

type ResourceResult struct {
	ID         int64
	CreatedOn  time.Time
	ModifiedOn time.Time
}

ResourceResult represents a definition of a resource that is identifiable and tracks creation/update timestamps.

func GetCreatedResourceResult

func GetCreatedResourceResult(rows *sqlx.Rows) (*ResourceResult, error)

GetCreatedResourceResult grabs the sequential id created_on and modified_on timestamps from the result rows returned from an INSERT...RETURNING query and closes the result set.

type RestfulLogAdapter added in v1.2.0

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

RestfulLogAdapter adapts go-restful logging to go-logging

func NewRestfulLogAdapter added in v1.2.1

func NewRestfulLogAdapter(logger *logging.Logger, logEndpoint bool) *RestfulLogAdapter

NewRestfulLogAdapter constructs and returns a new instance

func (*RestfulLogAdapter) Print added in v1.2.0

func (r *RestfulLogAdapter) Print(v ...interface{})

Print adapts the print call to a debug log

func (*RestfulLogAdapter) Printf added in v1.2.0

func (r *RestfulLogAdapter) Printf(format string, v ...interface{})

Printf adapts the printf call to a debugf log

type RestfulLoggingFilter added in v1.2.0

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

RestfulLoggingFilter is middleware that logs restful requests and response payloads

func NewRestfulLoggingFilter added in v1.2.0

func NewRestfulLoggingFilter(logger *logging.Logger) *RestfulLoggingFilter

NewRestfulLoggingFilter initializes a new logging filter instance

func (*RestfulLoggingFilter) Filter added in v1.2.0

func (r *RestfulLoggingFilter) Filter(request *restful.Request, response *restful.Response, chain *restful.FilterChain)

Filter is a filter function that logs before and after processing the request

func (*RestfulLoggingFilter) SetLogRoot added in v1.7.0

func (r *RestfulLoggingFilter) SetLogRoot(logRoot bool)

SetLogRoot toggles logging the root call (ping)

func (*RestfulLoggingFilter) SetRequestLogFormat added in v1.2.0

func (r *RestfulLoggingFilter) SetRequestLogFormat(format string)

SetRequestLogFormat sets the verbose request log format

func (*RestfulLoggingFilter) SetResponseLogFormat added in v1.2.0

func (r *RestfulLoggingFilter) SetResponseLogFormat(format string)

SetResponseLogFormat sets the verbose response log format

type ServiceConfig

type ServiceConfig struct {
	Endpoint            *EndpointConfig            `json:"endpoint"`
	DB                  *DBConfig                  `json:"db"`
	MigrationDB         *DBConfig                  `json:"migration_db"`
	Swagger             *SwaggerConfig             `json:"swagger"`
	Logging             *LoggingConfig             `json:"logging"`
	OAuth2Service       *OAuth2ServiceConfig       `json:"oauth2_service"`
	OpenIDConnectClient *OpenIDConnectClientConfig `json:"openid_connect_client"`
}

ServiceConfig represents a configuration suitable for fully configuration a service.

func NewServiceConfig

func NewServiceConfig() *ServiceConfig

NewServiceConfig intializes a new instance

func (*ServiceConfig) Validate

func (s *ServiceConfig) Validate() error

Validate validates a configuration, returning an error signaling invalid configuration

type StatsResource

type StatsResource struct {
	ServiceName      string    `json:"service_name" description:"The name of the service."`
	ServiceUptime    string    `json:"service_uptime" description:"The service uptime in unix format."`
	ServiceStartTime time.Time `json:"service_start_time" description:"Timestamp in UTC of when the service was first started."`
	ServiceVersion   string    `json:"service_version" description:"The version of the service binary."`
	CommitHash       string    `json:"commit_hash" description:"The git commit hash representing the sources built into the service binary."`
	APIVersion       string    `json:"api_version" description:"The version of the API (protocol)."`
}

StatsResource represents health stats that can be exposed as an API, useful for monitoring

func (*StatsResource) UpdateUptime

func (s *StatsResource) UpdateUptime()

UpdateUptime updates the service uptime based on the current time returned in a Unix standard uptime format.

type SwaggerConfig

type SwaggerConfig struct {
	APIPath         string `json:"api_path"`
	SwaggerPath     string `json:"swagger_path"`
	SwaggerFilePath string `json:"swagger_file_path"`
}

SwaggerConfig represents configuration to enable swagger documentation.

func (*SwaggerConfig) InstallSwaggerService

func (s *SwaggerConfig) InstallSwaggerService(info *spec.Info, securityDefinitions spec.SecurityDefinitions, security []map[string][]string, container *restful.Container)

InstallSwaggerService sets up and installs the swagger service

func (*SwaggerConfig) Validate

func (s *SwaggerConfig) Validate() error

Validate ensures the configuration is valid

type TokenAuthFilter added in v1.5.0

type TokenAuthFilter struct {
	URLWhiteList *URLWhiteList
	TokenManager *TokenManager
}

TokenAuthFilter represents a go-restful authentication filter that validates a JWT-Token passed via an http header parameter. There is an additional optionalwWhitelist that may be set, allowing specific urls, methods, or url patterns to opt-out of authentication.

func (*TokenAuthFilter) Filter added in v1.5.0

func (t *TokenAuthFilter) Filter(request *restful.Request, response *restful.Response, chain *restful.FilterChain)

Filter fits in the go-restful filterchain that encapsulates a token based authentication check.

type TokenManager added in v1.5.0

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

TokenManager generates and validates authentication tokens

func NewTokenManager added in v1.5.0

func NewTokenManager(signingKey []byte, tokenExpiration int) *TokenManager

NewTokenManager creates a new token manager with the given private key and token expiration (in seconds)

func (*TokenManager) CreateToken added in v1.5.0

func (t *TokenManager) CreateToken() (string, error)

CreateToken creates, signs and returns a new JSON Web Token using the signing key and expiration provided.

func (*TokenManager) TokenExpiration added in v1.6.1

func (t *TokenManager) TokenExpiration() int

TokenExpiration returns the token expiration value (in seconds)

func (*TokenManager) ValidateToken added in v1.5.0

func (t *TokenManager) ValidateToken(token string) error

ValidateToken validates the token, returning an error if validation fails.

type URLWhiteList added in v1.5.0

type URLWhiteList struct {
	Prefix string
	Suffix string
	// contains filtered or unexported fields
}

URLWhiteList represents a list of URLs and acceptable request methods per URL that can be matched against. A match is defined as one of the following a) the request method itself matches the global acceptAllMethods: (ie match "All OPTIONS requests") b) the url is an exact match and the request method matches one of the accepted methds mapped to the url. Url matching is done by matching each segment. Segments are separated by the slash character. '/' Url path variable tokens are supported, defaulted to using the : prefix to denote the path variable. Path variables match any value for the specific url segment in the Url. This can be customized by supplying custom Prefix and, optionally a custom Suffix All matching is case insensitve. Query parameters are stripped off prior to matching.

func NewURLWhiteList added in v1.5.0

func NewURLWhiteList() *URLWhiteList

NewURLWhiteList returns a new whitelist

func (*URLWhiteList) AcceptAll added in v1.5.0

func (u *URLWhiteList) AcceptAll(requestMethods ...string)

AcceptAll accepts all URLs for request methods. (ie if passing "OPTIONS", any options request is whitelisted)

func (*URLWhiteList) AddURL added in v1.5.0

func (u *URLWhiteList) AddURL(url string, requestMethods ...string)

AddURL adds an URL and its mapped request methods. If no methods are specified, any request method is allowed.

func (*URLWhiteList) Match added in v1.5.0

func (u *URLWhiteList) Match(url string, requestMethod string) bool

Match returns true if the url and requestMethod specified is a match, false otherwise.

type UnauthorizedError

type UnauthorizedError struct {
	Login string
	Err   error
}

UnauthorizedError represents unauthorized access to the system

func (*UnauthorizedError) Error

func (u *UnauthorizedError) Error() string

Error returns this error as a string

func (*UnauthorizedError) StatusCode

func (u *UnauthorizedError) StatusCode() int

StatusCode returns the HTTP status code appropriate for the error type

func (*UnauthorizedError) Unwrap

func (u *UnauthorizedError) Unwrap() error

Unwrap returns the underlying error

Jump to

Keyboard shortcuts

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