server

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 9, 2024 License: Apache-2.0 Imports: 20 Imported by: 161

Documentation

Overview

Package server provides a server implementation to connect network transport protocols and service business logic by defining server endpoints.

Index

Constants

This section is empty.

Variables

View Source
var (
	// CodeAccountExpired indicates the login attempt failed due to an expired account.
	CodeAccountExpired = "ACCOUNT_EXPIRED"
	// CodeFailure indicates the requested action failed.
	CodeFailure = "FAILURE"
	// CodeInvalidCredentials indicates the provided credentials are not valid.
	//nolint:gosec
	CodeInvalidCredentials = "INVALID_CREDENTIALS"
	// CodeNotSupported indicates that the resource is not supported.
	CodeNotSupported = "NOT_SUPPORTED"
	// CodeNotYetAvailable indicates that the API operation used is not ready yet.
	// Should occur with HTTP status code 503.
	CodeNotYetAvailable = "NOT_YET_AVAILABLE"
	// CodePermissionDenied indicates the provided credentials are valid, but the
	// requested resource requires other permissions.
	CodePermissionDenied = "PERMISSION_DENIED"
	// CodeResourceAlreadyExists indicates a resource does already exist.
	CodeResourceAlreadyExists = "RESOURCE_ALREADY_EXISTS"
	// CodeResourceCreated indicates a resource has been created.
	CodeResourceCreated = "RESOURCE_CREATED"
	// CodeResourceDeleted indicates a resource has been deleted.
	CodeResourceDeleted = "RESOURCE_DELETED"
	// CodeResourceDeletionStarted indicates a resource will be deleted.
	CodeResourceDeletionStarted = "RESOURCE_DELETION_STARTED"
	// CodeResourceNotFound indicates a resource could not be found.
	CodeResourceNotFound = "RESOURCE_NOT_FOUND"
	// CodeResourceUpdated indicates a resource has been updated.
	CodeResourceUpdated = "RESOURCE_UPDATED"
	// CodeSuccess indicates the requested action successed.
	CodeSuccess = "SUCCESS"
	// CodeTooManyRequests indicates the client is making too many requests.
	CodeTooManyRequests = "TOO_MANY_REQUESTS"
	// CodeImmutableAttribute indicates the provided data structure contains
	// fields that are immutable.
	CodeImmutableAttribute = "IMMUTABLE_ATTRIBUTE"
	// CodeUnknownAttribute indicates the provided data structure contains
	// unexpected fields.
	CodeUnknownAttribute = "UNKNOWN_ATTRIBUTE"
	// CodeInvalidInput indicates the user provided some input that does not
	// validate (usually HTTP status 400).
	CodeInvalidInput = "INVALID_INPUT"
	// CodeInternalError represents an error we don't want to give more details
	// about (usually HTTP status 500).
	CodeInternalError = "INTERNAL_ERROR"
)

Functions

func IsInvalidConfig

func IsInvalidConfig(err error) bool

IsInvalidConfig asserts invalidConfigError.

func IsInvalidContext

func IsInvalidContext(err error) bool

IsInvalidContext asserts invalidContextError.

func IsInvalidTransactionID

func IsInvalidTransactionID(err error) bool

IsInvalidTransactionID asserts invalidTransactionIDError.

func IsServerClosed

func IsServerClosed(err error) bool

IsServerClosed asserts serverClosedError.

Types

type Config

type Config struct {
	// ErrorEncoder is the server's error encoder. This wraps the error encoder
	// configured by the client. Clients should not implement error logging in
	// here them self. This is done by the server itself. Clients must not
	// implement error response writing them self. This is done by the server
	// itself. Duplicated response writing will lead to runtime panics.
	ErrorEncoder kithttp.ErrorEncoder
	// Logger is the logger used to print log messages.
	Logger micrologger.Logger
	// Router is a HTTP handler for the server. The returned router will have all
	// endpoints registered that are listed in the endpoint collection.
	Router *mux.Router

	// EnableDebugServer boolean flag to enable debug server on
	// http://127.0.0.1:6060/debug. This server is primarily used to expose
	// net/http/pprof.Handler.
	EnableDebugServer bool
	// Endpoints is the server's configured list of endpoints. These are the
	// custom endpoints configured by the client.
	Endpoints []Endpoint
	// HandlerWrapper is a wrapper provided to interact with the request on its
	// roots.
	HandlerWrapper func(h http.Handler) http.Handler
	// ListenAddress is the address the server is listening on.
	ListenAddress string
	// ListenMetricsAddress is an optional address where the server will expose the
	// `/metrics` endpoint for prometheus scraping. When left blank the `/metrics`
	// endpoint will be available at the ListenAddress.
	ListenMetricsAddress string
	// LogAccess decides whether to emit logs for each requested route.
	LogAccess bool
	// RequestFuncs is the server's configured list of request functions. These
	// are the custom request functions configured by the client.
	RequestFuncs []kithttp.RequestFunc
	// ServiceName is the name of the micro-service implementing the microkit
	// server. This is used for logging and instrumentation.
	ServiceName string
	// TLSCAFile is the file path to the certificate root CA file, if any.
	TLSCAFile string
	// TLSKeyFilePath is the file path to the certificate public key file, if any.
	TLSCrtFile string
	// TLSKeyFilePath is the file path to the certificate private key file, if
	// any.
	TLSKeyFile string
	// Viper is a configuration management object.
	Viper *viper.Viper
}

type Endpoint

type Endpoint interface {
	// Decoder returns the kithttp.DecodeRequestFunc used to decode a request
	// before the actual endpoint is executed.
	Decoder() kithttp.DecodeRequestFunc
	// Decoder returns the kithttp.EncodeResponseFunc used to encode a response
	// after the actual endpoint was executed.
	Encoder() kithttp.EncodeResponseFunc
	// Endpoint returns the kitendpoint.Endpoint which receives a decoded response
	// and forwards any workload to the internal service object reference.
	Endpoint() kitendpoint.Endpoint
	// Method returns the HTTP verb used to register the endpoint.
	Method() string
	// Middlewares returns the middlewares the endpoint configures to be run
	// before the actual endpoint is being invoked.
	Middlewares() []kitendpoint.Middleware
	// Name returns the name of the endpoint which can be used to label metrics or
	// annotate logs.
	Name() string
	// Path returns the HTTP request URL path used to register the endpoint.
	Path() string
}

Endpoint represents the management of transport logic. An endpoint defines what it needs to work properly. Internally it holds a reference to the service object which implements business logic and executes any workload. That means that network transport and business logic are strictly separated and work hand in hand via well defined package APIs.

type ResponseError

type ResponseError interface {
	// Code returns the code being tracked using SetCode. If this code is not set
	// using SetCode it defaults to CodeInternalError.
	Code() string
	// Error returns the message of the underlying error.
	Error() string
	// Message returns the message being tracked using SetMessage. If this message
	// is not set using SetMessage it defaults to the error message of the
	// underlying error.
	Message() string
	// SetCode tracks the given response code for the current response error. The
	// given response code will be used for logging, instrumentation and response
	// creation.
	SetCode(code string)
	// SetMessage tracks the given response message for the current response
	// error. The given response message will be used for response creation.
	SetMessage(message string)
	// Underlying returns the actual underlying error, which is expected to be of
	// type kithttp.Error.
	Underlying() error
}

ResponseError is a wrapper for errors passed to the client's error encoder to propagate specific response information in error cases.

func NewResponseError

func NewResponseError(config ResponseErrorConfig) (ResponseError, error)

New creates a new configured response error.

type ResponseErrorConfig

type ResponseErrorConfig struct {
	// Settings.
	Underlying error
}

ResponseErrorConfig represents the configuration used to create a new response error.

func DefaultResponseErrorConfig

func DefaultResponseErrorConfig() ResponseErrorConfig

DefaultResponseErrorConfig provides a default configuration to create a new response error by best effort.

type ResponseWriter

type ResponseWriter interface {
	// BodyBuffer returns the buffer which is used to track the bytes being
	// written to the response.
	BodyBuffer() *bytes.Buffer
	// HasWritten expresses whether the underlying response writer has already
	// written anything to the response body.
	HasWritten() bool
	// Header is only a wrapper around http.ResponseWriter.Header.
	Header() http.Header
	// StatusCode returns either the default status code of the one that was
	// actually written using WriteHeader.
	StatusCode() int
	// Write is only a wrapper around http.ResponseWriter.Write.
	Write(b []byte) (int, error)
	// WriteHeader is a wrapper around http.ResponseWriter.Write. In addition to
	// that it is used to track the written status code.
	WriteHeader(c int)
}

ResponseWriter is a wrapper for http.ResponseWriter to track the written status code.

func NewResponseWriter

func NewResponseWriter(config ResponseWriterConfig) (ResponseWriter, error)

New creates a new configured response writer.

type ResponseWriterConfig

type ResponseWriterConfig struct {
	// Settings.
	BodyBuffer     *bytes.Buffer
	ResponseWriter http.ResponseWriter
	StatusCode     int
}

ResponseWriterConfig represents the configuration used to create a new response writer.

func DefaultResponseWriterConfig

func DefaultResponseWriterConfig() ResponseWriterConfig

DefaultResponseWriterConfig provides a default configuration to create a new response writer by best effort.

type Server

type Server interface {
	// Boot registers the configured endpoints and starts the server under the
	// configured address.
	Boot()
	// Config returns the servers configuration as given by the client.
	Config() Config
	// Shutdown stops the running server gracefully.
	Shutdown()
}

Server manages the HTTP transport logic.

func New

func New(config Config) (Server, error)

New creates a new configured server object.

Jump to

Keyboard shortcuts

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