goserv

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Jan 10, 2020 License: Apache-2.0 Imports: 17 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 = "[%s %s] request\n"
	// DefaultVerboseRequestLogFormat format
	DefaultVerboseRequestLogFormat = "" /* 176-byte string literal not displayed */
	// DefaultResponseLogFormat format
	DefaultResponseLogFormat = "[%s %s] response\n\tstatus='%d'\n\tresponse_time='%s'\n"
	// DefaultVerboseResponseLogFormat format
	DefaultVerboseResponseLogFormat = "[%s %s] response headers:\n%s\n"
)

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 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 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) SetRequestLogFormat added in v1.2.0

func (r *RestfulLoggingFilter) SetRequestLogFormat(format string)

SetRequestLogFormat sets the request log format

func (*RestfulLoggingFilter) SetResponseLogFormat added in v1.2.0

func (r *RestfulLoggingFilter) SetResponseLogFormat(format string)

SetResponseLogFormat sets the response log format

func (*RestfulLoggingFilter) SetVerboseRequestLogFormat added in v1.2.0

func (r *RestfulLoggingFilter) SetVerboseRequestLogFormat(format string)

SetVerboseRequestLogFormat sets the verbose request log format

func (*RestfulLoggingFilter) SetVerboseResponseLogFormat added in v1.2.0

func (r *RestfulLoggingFilter) SetVerboseResponseLogFormat(format string)

SetVerboseResponseLogFormat 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"`
	Custom      map[string]interface{} `json:"custom"`
	// contains filtered or unexported fields
}

ServiceConfig represents a configuration suitable for fully configuration a service.

func NewServiceConfig

func NewServiceConfig() *ServiceConfig

NewServiceConfig intializes a new instance

func (*ServiceConfig) SetCustomValidator

func (s *ServiceConfig) SetCustomValidator(f func(map[string]interface{}) error)

SetCustomValidator sets a function that is executed during validation that validates any custom configuration

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, 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 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