webserver

package module
v1.2.3 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2023 License: BSD-3-Clause Imports: 25 Imported by: 9

README

web-server

Build Status GoDoc Go Report Card Coverage

This library is provided as a wrapper utility for quickly create and host your web services.

Original source: https://github.com/zhongjie-cai/web-server

Library dependencies (must be present in vendor folder or in Go path):

  • UUID: go get -u github.com/google/uuid
  • MUX: go get -u github.com/gorilla/mux
  • Testify: go get -u github.com/stretchr/testify (For tests only)

A sample application is shown below:

main.go

package main

import (
	"fmt"
	"net/http"

	webserver "github.com/zhongjie-cai/web-server"
)

// This is a sample of how to setup application for running the server
func main() {
	var application = webserver.NewApplication(
		"my web server",
		18605,
		"0.0.1",
		&myCustomization{},
	)
	defer application.Stop()
	application.Start()
}

// myCustomization inherits from the default customization so you can skip setting up all customization methods
//   alternatively, you could bring in your own struct that instantiate the webserver.Customization interface to have a verbosed control over what to customize
type myCustomization struct {
	webserver.DefaultCustomization
}

func (customization *myCustomization) Log(session webserver.Session, logType webserver.LogType, logLevel webserver.LogLevel, category, subcategory, description string) {
	fmt.Printf("[%v|%v] <%v|%v> %v\n", logType, logLevel, category, subcategory, description)
}

func (customization *myCustomization) Middlewares() []webserver.MiddlewareFunc {
	return []webserver.MiddlewareFunc{
		loggingRequestURIMiddleware,
	}
}

func (customization *myCustomization) Statics() []webserver.Static {
	return []webserver.Static{
		webserver.Static{
			Name:       "SwaggerUI",
			PathPrefix: "/docs/",
			Handler:    swaggerHandler(),
		},
		webserver.Static{
			Name:       "SwaggerRedirect",
			PathPrefix: "/docs",
			Handler:    swaggerRedirect(),
		},
	}
}
func (customization *myCustomization) Routes() []webserver.Route {
	return []webserver.Route{
		webserver.Route{
			Endpoint:   "Health",
			Method:     http.MethodGet,
			Path:       "/health",
			ActionFunc: getHealth,
		},
	}
}

// getHealth is an example of how a normal HTTP handling method is written with this library
func getHealth(
	session webserver.Session,
) (interface{}, error) {
	var appVersion = "some application version"
	session.LogMethodLogic(
		webserver.LogLevelWarn,
		"Health",
		"Summary",
		"AppVersion = %v",
		appVersion,
	)
	return appVersion, nil
}

// swaggerRedirect is an example of how an HTTP redirection could be managed with this library
func swaggerRedirect() http.Handler {
	return http.RedirectHandler(
		"/docs/",
		http.StatusPermanentRedirect,
	)
}

// swaggerHandler is an example of how a normal HTTP static content hosting is written with this library
func swaggerHandler() http.Handler {
	return http.StripPrefix(
		"/docs/",
		http.FileServer(
			http.Dir("./docs"),
		),
	)
}

// loggingRequestURIMiddleware is an example of how a middleware function is written with this library
func loggingRequestURIMiddleware(nextHandler http.Handler) http.Handler {
	return http.HandlerFunc(
		func(
			responseWriter http.ResponseWriter,
			httpRequest *http.Request,
		) {
			// middleware logic & processing
			fmt.Println(httpRequest.RequestURI)
			// hand over to next handler in the chain
			nextHandler.ServeHTTP(responseWriter, httpRequest)
		},
	)
}

Request & Response

The registered handler could retrieve request body, parameters and query strings through session methods, thus it is normally not necessary to load request from session:

// request body: {"foo":"bar","test":123}
var body struct {
	Foo string `json:"foo"`
	Test int `json:"test"`
}
var bodyError = session.GetRequestBody(&body)

// parameters: "id"=456
var id int
var idError = session.GetRequestParameter("id", &id)

// query strigns: "uuid"="123456-1234-1234-1234-123456789abc"
var uuid uuid.UUID
var uuidError = session.GetRequestQuery("uuid", 0, &uuid)

However, if specific data is needed from request, one could always retrieve request from session through following function call using session object:

var httpRequest = session.GetRequest()

The response functions accept the session ID and internally load the response writer accordingly, thus it is normally not necessary to load response writer from session.

However, if specific operation is needed for response, one could always retrieve response writer through following function call using session object:

var responseWriter = session.GetResponseWriter()

After your customized operations on the response writer, use the following as return type in the handler function to enforce the library to skip any unnecessary handling of the HTTP response writer:

return webserver.SkipResponseHandling()

Error Handling

To simplify the error handling, one could utilize the built-in error interface AppError, which provides support to many basic types of errors that are mapped to corresponding HTTP status codes:

  • BadRequest => BadRequest (400)
  • Unauthorized => Unauthorized (401)
  • CircuitBreak => Forbidden (403)
  • AccessForbidden => Forbidden (403)
  • NotFound => NotFound (404)
  • InvalidOperation => MethodNotAllowed (405)
  • DataCorruption => Conflict (409)
  • OperationLock => Locked (423)
  • GeneralFailure => InternalServerError (500)
  • NotImplemented => NotImplemented (501)

If you bring in your own implementation for the error interface AppHTTPError, the web server engine could automatically utilise the corresponding methods to translate an AppHTTPError into HTTP status code and response message:

HTTPStatusCode() int
HTTPResponseMessage() string

However, if specific operation is needed for response, one could always customize the error interpretation by customizing the InterpretError function:

func (customization *myCustomization) InterpretError(err error) (statusCode int, responseMessage string) {
	return 500, err.Error()
}

Logging

The library allows the user to customize its logging function by customizing the Log method. The logging is split into two management areas: log type and log level.

Log Type

The log type definitions can be found under the logType.go file. Apart from all Method-prefixed log types, all remainig log types are managed by the library internally and should not be worried by the consumer.

Log Level

The log level definitions can be found under the logLevel.go file. Log level only affects all Method-prefixed log types; for all other log types, the log level is default to Info.

Session Logging

The registered session allows the user to add manual logging to its codebase, through several listed methods as

session.LogMethodEnter()
session.LogMethodParameter(parameters ...interface{})
session.LogMethodLogic(logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{})
session.LogMethodReturn(returns ...interface{})
session.LogMethodExit()

The Enter, Parameter, Return and Exit are limited to the scope of method boundary area loggings. The Logic is the normal logging that can be used in any place at any level in the codebase to enforce the user's customized logging entries.

Session Attachment

The registered session contains an attachment dictionary, which allows the user to attach any object which is JSON serializable into the given session associated to a session ID.

var myAttachmentName = "my attachment name"
var myAttachmentObject = anyJSONSerializableStruct {
	...
}
var success = session.Attach(myAttachmentName, myAttachmentObject)
if !success {
	// failed to attach an object: add your customized logic here if needed
} else {
	// succeeded to attach an object: add your customized logic here if needed
}

To retrieve a previously attached object from session, simply use the following sample logic.

var myAttachmentName = "my attachment name"
var retrievedAttachment anyJSONSerializableStruct
var success = session.GetAttachment(myAttachmentName, &retrievedAttachment)
if !success {
	// failed to retrieve an attachment: add your customized logic here if needed
} else {
	// succeeded to retrieve an attachment: add your customized logic here if needed
}

In some situations, it is good to detach a certain attachment, especially if it is a big object consuming large memory, which can be done as following.

var myAttachmentName = "my attachment name"
var success = session.Detach(myAttachmentName)
if !success {
	// failed to detach an attachment: add your customized logic here if needed
} else {
	// succeeded to detach an attachment: add your customized logic here if needed
}

External Webcall Requests

The library provides a way to send out HTTP/HTTPS requests to external web services based on current session. Using this provided feature ensures the logging of the web service requests into corresponding log type for the given session.

You can reuse a same struct for multiple HTTP status codes, as long as the structures in JSON format are compatible. If there is no receiver entry registered for a particular HTTP status code, the corresponding response body is ignored for deserialization when that HTTP status code is received.

...

var webcallRequest = session.CreateWebcallRequest(
	HTTP.POST,                       // Method
	"https://www.example.com/tests", // URL
	"{\"foo\":\"bar\"}",             // Payload
	true,                            // SendClientCert
)
var responseOn200 responseOn200Struct
var responseOn400 responseOn400Struct
var responseOn500 responseOn500Struct
webcallRequest.AddHeader(
	"Content-Type",
	"application/json",
).AddHeader(
	"Accept",
	"application/json",
).Anticipate(
	http.StatusOK,
	http.StatusBadRequest,
	&responseOn200,
).Anticipate(
	http.StatusBadRequest,
	http.StatusInternalServerError,
	&responseOn400,
).Anticipate(
	http.StatusInternalServerError,
	999,
	&responseOn500,
)
var statusCode, responseHeader, responseError = webcallRequest.Process()

...

Webcall requests would send out client certificate for mTLS communications if the following customization is in place.

func (customization *myCustomization) ClientCert() *tls.Certificate {
    return ... // replace with however you would load the client certificate
}

Webcall requests could also be customized for:

HTTP Client's HTTP Transport (http.RoundTripper)

This is to enable the 3rd party monitoring libraries, e.g. new relic, to wrap the HTTP transport for better handling of webcall communications.

func (customization *myCustomization) RoundTripper(originalTransport http.RoundTripper) http.RoundTripper {
	return ... // replace with whatever round trip wrapper logic you would like to have
}

HTTP Request (http.Request)

This is to enable the 3rd party monitoring libraries, e.g. new relic, to wrap individual HTTP request for better handling of web requests.

func (customization *myCustomization) WrapRequest(session Session, httpRequest *http.Request) *http.Request {
	return ... // replace with whatever HTTP request wrapper logic you would like to have
}

Webcall Timeout

This is to provide the default HTTP request timeouts for HTTP Client over all webcall communications.

func (customization *myCustomization) DefaultTimeout() time.Duration {
	return 3 * time.Minute // replace with whatever timeout duration you would like to have
}

Documentation

Index

Constants

View Source
const (
	ContentTypeJSON = "application/json; charset=utf-8"
)

These are the constants used by the HTTP modules

Variables

This section is empty.

Functions

func SkipResponseHandling added in v1.1.5

func SkipResponseHandling() (interface{}, error)

SkipResponseHandling indicates to the library to skip operating on the HTTP response writer

Types

type ActionFunc

type ActionFunc func(
	session Session,
) (
	responseObject interface{},
	responseError error,
)

ActionFunc defines the action function to be called for route processing logic

type AppBaseError

type AppBaseError interface {
	// Error refers to the Golang built-in error interface method
	Error() string
	// ErrorCode returns the string representation of the error code enum
	ErrorCode() string
}

AppBaseError is the error extending interface that is compatible with Golang error type

type AppContainerError

type AppContainerError interface {
	// Contains checks if the current error object or any of its inner errors contains the given error object
	Contains(err error) bool
	// Wrap wraps the given list of inner errors into the current app error object
	Wrap(innerErrors ...error) AppError
}

AppContainerError is the error extending interface that can be used to wrap inner errors

type AppError

type AppError interface {
	// AppBaseError is the error extending interface that is compatible with Golang error type
	AppBaseError
	// AppHTTPError is the error extending interface that can be translated into HTTP status code and response body
	AppHTTPError
	// AppContainerError is the error extending interface that can be used to wrap inner errors
	AppContainerError
}

AppError is the error wrapper interface for all web service generated errors

func GetAccessForbidden

func GetAccessForbidden(errorMessage string, innerErrors ...error) AppError

GetAccessForbidden creates an error related to AccessForbidden

func GetBadRequest

func GetBadRequest(errorMessage string, innerErrors ...error) AppError

GetBadRequest creates an error related to BadRequest

func GetCircuitBreak

func GetCircuitBreak(errorMessage string, innerErrors ...error) AppError

GetCircuitBreak creates an error related to CircuitBreak

func GetDataCorruption

func GetDataCorruption(errorMessage string, innerErrors ...error) AppError

GetDataCorruption creates an error related to DataCorruption

func GetGeneralFailure

func GetGeneralFailure(errorMessage string, innerErrors ...error) AppError

GetGeneralFailure creates a generic error based on GeneralFailure

func GetInvalidOperation

func GetInvalidOperation(errorMessage string, innerErrors ...error) AppError

GetInvalidOperation creates an error related to InvalidOperation

func GetNotFound

func GetNotFound(errorMessage string, innerErrors ...error) AppError

GetNotFound creates an error related to NotFound

func GetNotImplemented

func GetNotImplemented(errorMessage string, innerErrors ...error) AppError

GetNotImplemented creates an error related to NotImplemented

func GetOperationLock

func GetOperationLock(errorMessage string, innerErrors ...error) AppError

GetOperationLock creates an error related to OperationLock

func GetUnauthorized

func GetUnauthorized(errorMessage string, innerErrors ...error) AppError

GetUnauthorized creates an error related to Unauthorized

func WrapError

func WrapError(sourceError error, innerErrors ...error) AppError

WrapError wraps the given error with all provided inner errors

type AppHTTPError

type AppHTTPError interface {
	// HTTPStatusCode returns the corresponding HTTP status code mapped to the error code value
	HTTPStatusCode() int
	// HTTPResponseMessage returns the JSON representation of this error for HTTP response
	HTTPResponseMessage() string
}

AppHTTPError is the error extending interface that can be translated into HTTP status code and response body

type Application

type Application interface {
	// Start starts the web server hosting in the current running thread, causing the thread to be blocked until a Stop is called or an interrupt signal is received
	Start()
	// Session retrieves the application-level session instance for logging or any other necessary operations
	Session() Session
	// IsRunning returns true if the server has been successfully started and is currently running
	IsRunning() bool
	// Stop interrupts the web server hosting, causing the web server to gracefully shutdown; a synchronous Start would then return, or an asynchronous StartSync would mark its wait group done and then return
	Stop()
}

Application is the interface for web server application

func NewApplication

func NewApplication(
	name string,
	address string,
	version string,
	customization Customization,
) Application

NewApplication creates a new application for web server hosting

type BootstrapCustomization

type BootstrapCustomization interface {
	// PreBootstrap is to customize the pre-processing logic before bootstrapping
	PreBootstrap() error

	// PostBootstrap is to customize the post-processing logic after bootstrapping
	PostBootstrap() error

	// AppClosing is to customize the application closing logic after server shutdown
	AppClosing() error
}

BootstrapCustomization holds customization methods related to bootstrapping

type Customization

type Customization interface {
	// BootstrapCustomization holds customization methods related to bootstrapping
	BootstrapCustomization
	// LoggingCustomization holds customization methods related to logging
	LoggingCustomization
	// HostingCustomization holds customization methods related to hosting
	HostingCustomization
	// HandlerCustomization holds customization methods related to handlers
	HandlerCustomization
	// WebRequestCustomization holds customization methods related to web requests
	WebRequestCustomization
}

Customization holds all customization methods

type DefaultCustomization

type DefaultCustomization struct{}

DefaultCustomization can be used for easier customization override

func (*DefaultCustomization) AppClosing

func (customization *DefaultCustomization) AppClosing() error

AppClosing is to customize the application closing logic after server shutdown

func (*DefaultCustomization) CaCertPool

func (customization *DefaultCustomization) CaCertPool() *x509.CertPool

CaCertPool is to customize the CA cert pool for incoming client certificate validation; if not set or nil, no validation is conducted for incoming client certificates

func (*DefaultCustomization) ClientCert

func (customization *DefaultCustomization) ClientCert() *tls.Certificate

ClientCert is to customize the client certificate for external requests; if not set or nil, no client certificate is sent to external web services

func (*DefaultCustomization) DefaultTimeout

func (customization *DefaultCustomization) DefaultTimeout() time.Duration

DefaultTimeout is to customize the default timeout for any webcall communications through HTTP/HTTPS by session

func (*DefaultCustomization) GraceShutdownWaitTime

func (customization *DefaultCustomization) GraceShutdownWaitTime() time.Duration

GraceShutdownWaitTime is to customize the graceful shutdown wait time for the application

func (*DefaultCustomization) InstrumentRouter

func (customization *DefaultCustomization) InstrumentRouter(router *mux.Router) *mux.Router

InstrumentRouter is to customize the instrumentation on top of a fully configured router; usually useful for 3rd party monitoring tools such as new relic, etc.

func (*DefaultCustomization) InterpretError

func (customization *DefaultCustomization) InterpretError(err error) (int, string)

InterpretError is to customize how application interpret an error into HTTP status code and corresponding status message

func (*DefaultCustomization) InterpretSuccess

func (customization *DefaultCustomization) InterpretSuccess(responseContent interface{}) (int, string)

InterpretSuccess is to customize how application interpret a response content into HTTP status code and corresponding response body

func (*DefaultCustomization) Listener added in v1.2.3

func (customization *DefaultCustomization) Listener() net.Listener

Listener is to customize the override of net.Listener to be used by http.Serve and http.ServeTLS; usually useful with UDS connections for local web server

func (*DefaultCustomization) Log

func (customization *DefaultCustomization) Log(session Session, logType LogType, logLevel LogLevel, category, subcategory, description string)

Log is to customize the logging backend for the whole application

func (*DefaultCustomization) MethodNotAllowedHandler

func (customization *DefaultCustomization) MethodNotAllowedHandler() http.Handler

MethodNotAllowedHandler is to customize the handler to be used when the request method does not match the route

func (*DefaultCustomization) Middlewares

func (customization *DefaultCustomization) Middlewares() []MiddlewareFunc

Middlewares is to customize the middlewares registration

func (*DefaultCustomization) NotFoundHandler

func (customization *DefaultCustomization) NotFoundHandler() http.Handler

NotFoundHandler is to customize the handler to be used when no route matches.

func (*DefaultCustomization) PostAction

func (customization *DefaultCustomization) PostAction(session Session) error

PostAction is to customize the post-action used after each route action takes place, e.g. finalization, etc.

func (*DefaultCustomization) PostBootstrap

func (customization *DefaultCustomization) PostBootstrap() error

PostBootstrap is to customize the post-processing logic after bootstrapping

func (*DefaultCustomization) PreAction

func (customization *DefaultCustomization) PreAction(session Session) error

PreAction is to customize the pre-action used before each route action takes place, e.g. authorization, etc.

func (*DefaultCustomization) PreBootstrap

func (customization *DefaultCustomization) PreBootstrap() error

PreBootstrap is to customize the pre-processing logic before bootstrapping

func (*DefaultCustomization) RecoverPanic

func (customization *DefaultCustomization) RecoverPanic(session Session, recoverResult interface{}) (interface{}, error)

RecoverPanic is to customize the recovery of panic into a valid response and error in case it happens (for recoverable panic only)

func (*DefaultCustomization) RoundTripper

func (customization *DefaultCustomization) RoundTripper(originalTransport http.RoundTripper) http.RoundTripper

RoundTripper is to customize the creation of the HTTP transport for any webcall communications through HTTP/HTTPS by session

func (*DefaultCustomization) Routes

func (customization *DefaultCustomization) Routes() []Route

Routes is to customize the routes registration

func (*DefaultCustomization) ServerCert

func (customization *DefaultCustomization) ServerCert() *tls.Certificate

ServerCert is to customize the server certificate for application; also determines the server hosting security option (HTTP v.s. HTTPS)

func (*DefaultCustomization) SkipServerCertVerification

func (customization *DefaultCustomization) SkipServerCertVerification() bool

SkipServerCertVerification is to customize the skip of server certificate verification for any webcall communications through HTTP/HTTPS by session

func (*DefaultCustomization) Statics

func (customization *DefaultCustomization) Statics() []Static

Statics is to customize the static contents registration

func (*DefaultCustomization) WrapHandler added in v1.1.3

func (customization *DefaultCustomization) WrapHandler(handler http.Handler) http.Handler

WrapHandler is to customize the overall wrapping of http.Handler before the server is configured

func (*DefaultCustomization) WrapRequest

func (customization *DefaultCustomization) WrapRequest(session Session, httpRequest *http.Request) *http.Request

WrapRequest is to customize the creation of the HTTP request for any webcall communications through HTTP/HTTPS by session; utilize this method if needed for new relic wrapping, etc.

type HandlerCustomization

type HandlerCustomization interface {
	// PreAction is to customize the pre-action used before each route action takes place, e.g. authorization, etc.
	PreAction(session Session) error

	// PostAction is to customize the post-action used after each route action takes place, e.g. finalization, etc.
	PostAction(session Session) error

	// InterpretSuccess is to customize how application interpret a response content into HTTP status code and corresponding response body
	InterpretSuccess(responseContent interface{}) (int, string)

	// InterpretError is to customize how application interpret an error into HTTP status code and corresponding response body
	InterpretError(err error) (int, string)

	// RecoverPanic is to customize the recovery of panic into a valid response and error in case it happens (for recoverable panic only)
	RecoverPanic(session Session, recoverResult interface{}) (interface{}, error)

	// NotFoundHandler is to customize the handler to be used when no route matches.
	NotFoundHandler() http.Handler

	// MethodNotAllowed is to customize the handler to be used when the request method does not match the route
	MethodNotAllowedHandler() http.Handler
}

HandlerCustomization holds customization methods related to handlers

type HostingCustomization

type HostingCustomization interface {
	// ServerCert is to customize the server certificate for application; also determines the server hosting security option (HTTP v.s. HTTPS)
	ServerCert() *tls.Certificate

	// CaCertPool is to customize the CA cert pool for incoming client certificate validation; if not set or nil, no validation is conducted for incoming client certificates
	CaCertPool() *x509.CertPool

	// GraceShutdownWaitTime is to customize the graceful shutdown wait time for the application
	GraceShutdownWaitTime() time.Duration

	// Routes is to customize the routes registration
	Routes() []Route

	// Statics is to customize the static contents registration
	Statics() []Static

	// Middlewares is to customize the middlewares registration
	Middlewares() []MiddlewareFunc

	// InstrumentRouter is to customize the instrumentation on top of a fully configured router; usually useful for 3rd party monitoring tools such as new relic, etc.
	InstrumentRouter(router *mux.Router) *mux.Router

	// WrapHandler is to customize the overall wrapping of http.Handler before the server is configured
	WrapHandler(handler http.Handler) http.Handler

	// Listener is to customize the override of net.Listener to be used by http.Serve and http.ServeTLS; usually useful with UDS connections for local web server
	Listener() net.Listener
}

HostingCustomization holds customization methods related to hosting

type LogLevel

type LogLevel int

LogLevel is the severity level of logging

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
	LogLevelFatal
)

These are the enum definitions of log types and presets

func NewLogLevel

func NewLogLevel(value string) LogLevel

NewLogLevel converts a string representation of LogLevel flag to its strongly typed instance

func (LogLevel) String

func (logLevel LogLevel) String() string

FromString converts a LogLevel flag instance to its string representation

type LogType

type LogType int

LogType is the entry type of logging

const (
	LogTypeEndpointEnter LogType = 1 << iota
	LogTypeEndpointRequest
	LogTypeMethodEnter
	LogTypeMethodParameter
	LogTypeMethodLogic
	LogTypeWebcallStart
	LogTypeWebcallRequest
	LogTypeWebcallResponse
	LogTypeWebcallFinish
	LogTypeMethodReturn
	LogTypeMethodExit
	LogTypeEndpointResponse
	LogTypeEndpointExit

	LogTypeBasicTracing   LogType = LogTypeMethodLogic
	LogTypeGeneralTracing LogType = LogTypeBasicTracing | LogTypeEndpointEnter | LogTypeEndpointExit
	LogTypeVerboseTracing LogType = LogTypeGeneralTracing | LogTypeWebcallStart | LogTypeWebcallFinish
	LogTypeFullTracing    LogType = LogTypeVerboseTracing | LogTypeMethodEnter | LogTypeMethodExit

	LogTypeBasicDebugging   LogType = LogTypeMethodLogic
	LogTypeGeneralDebugging LogType = LogTypeBasicDebugging | LogTypeEndpointRequest | LogTypeEndpointResponse
	LogTypeVerboseDebugging LogType = LogTypeGeneralDebugging | LogTypeWebcallRequest | LogTypeWebcallResponse
	LogTypeFullDebugging    LogType = LogTypeVerboseDebugging | LogTypeMethodParameter | LogTypeMethodReturn

	LogTypeBasicLogging   LogType = LogTypeBasicTracing | LogTypeBasicDebugging
	LogTypeGeneralLogging LogType = LogTypeBasicLogging | LogTypeGeneralTracing | LogTypeGeneralDebugging
	LogTypeVerboseLogging LogType = LogTypeGeneralLogging | LogTypeVerboseTracing | LogTypeVerboseDebugging
	LogTypeFullLogging    LogType = LogTypeVerboseLogging | LogTypeFullTracing | LogTypeFullDebugging

	LogTypeAppRoot LogType = 0
)

These are the enum definitions of log types and presets

func NewLogType

func NewLogType(value string) LogType

NewLogType converts a string representation of LogType flag to its strongly typed instance

func (LogType) HasFlag

func (logtype LogType) HasFlag(flag LogType) bool

HasFlag checks whether this log category has the flag set or not

func (LogType) String

func (logtype LogType) String() string

FromString converts a LogType flag instance to its string representation

type LoggingCustomization

type LoggingCustomization interface {
	// Log is to customize the logging backend for the whole application
	Log(session Session, logType LogType, logLevel LogLevel, category, subcategory, description string)
}

LoggingCustomization holds customization methods related to logging

type MiddlewareFunc

type MiddlewareFunc mux.MiddlewareFunc

MiddlewareFunc warps around mux.MiddlewareFunc, which receives an http.Handler and returns another http.Handler. Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc.

type ParameterType

type ParameterType string

ParameterType defines the type specification of a route parameter

const (
	ParameterTypeAnything ParameterType = `.*`
	ParameterTypeString   ParameterType = `\w+`
	ParameterTypeInteger  ParameterType = `\d+`
	ParameterTypeUUID     ParameterType = `[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}`
	ParameterTypeDate     ParameterType = `\d{4}-\d{2}-\d{2}`
	ParameterTypeTime     ParameterType = `\d{2}:\d{2}:\d{2}(?:\.\d+)?`
	ParameterTypeDateTime ParameterType = ParameterTypeDate + `T` + ParameterTypeTime + `(?:Z|[+-]\d{2}:\d{2})`
	ParameterTypeBoolean  ParameterType = `(?i)(?:true|false)`
	ParameterTypeFloat    ParameterType = `\d+(?:\.\d+)?`
)

These are constants for parameter types and their corresponding replacement RegExp statements

func (*ParameterType) Evaludate

func (parameterType *ParameterType) Evaludate(value string) (bool, error)

Evaludate evaluates the given value against the parameter type's defined regex expression and returns whether or not the regex matches

type Route

type Route struct {
	Endpoint   string
	Method     string
	Path       string
	Parameters map[string]ParameterType
	Queries    map[string]ParameterType
	ActionFunc ActionFunc
}

Route holds the registration information of a dynamic route hosting

type Session

Session is the storage for the current HTTP request session, containing information needed for logging, monitoring, etc.

type SessionAttachment

type SessionAttachment interface {
	// Attach attaches any value object into the given session associated to the session ID
	Attach(name string, value interface{}) bool

	// Detach detaches any value object from the given session associated to the session ID
	Detach(name string) bool

	// GetRawAttachment retrieves any value object from the given session associated to the session ID and returns the raw interface (consumer needs to manually cast, but works for struct with private fields)
	GetRawAttachment(name string) (interface{}, bool)

	// GetAttachment retrieves any value object from the given session associated to the session ID and unmarshals the content to given data template (only works for structs with exported fields)
	GetAttachment(name string, dataTemplate interface{}) bool
}

SessionAttachment is a subset of Session interface, containing only attachment related methods

type SessionHTTP

type SessionHTTP interface {
	SessionHTTPRequest
	SessionHTTPResponse
}

SessionHTTP is a subset of Session interface, containing only HTTP request & response related methods

type SessionHTTPRequest

type SessionHTTPRequest interface {
	// GetRequest returns the HTTP request object from session object for given session ID
	GetRequest() *http.Request

	// GetRequestBody loads HTTP request body associated to session and unmarshals the content JSON to given data template
	GetRequestBody(dataTemplate interface{}) error

	// GetRequestParameter loads HTTP request parameter associated to session for given name and unmarshals the content to given data template
	GetRequestParameter(name string, dataTemplate interface{}) error

	// GetRequestQuery loads HTTP request single query string associated to session for given name and unmarshals the content to given data template
	GetRequestQuery(name string, index int, dataTemplate interface{}) error

	// GetRequestHeader loads HTTP request single header string associated to session for given name and unmarshals the content to given data template
	GetRequestHeader(name string, index int, dataTemplate interface{}) error
}

SessionHTTPRequest is a subset of Session interface, containing only HTTP request related methods

type SessionHTTPResponse

type SessionHTTPResponse interface {
	// GetResponseWriter returns the HTTP response writer object from session object for given session ID
	GetResponseWriter() http.ResponseWriter
}

SessionHTTPResponse is a subset of SessionHTTP interface, containing only HTTP response related methods

type SessionLogging

type SessionLogging interface {
	// LogMethodEnter sends a logging entry of MethodEnter log type for the given session associated to the session ID
	LogMethodEnter()

	// LogMethodParameter sends a logging entry of MethodParameter log type for the given session associated to the session ID
	LogMethodParameter(parameters ...interface{})

	// LogMethodLogic sends a logging entry of MethodLogic log type for the given session associated to the session ID
	LogMethodLogic(logLevel LogLevel, category string, subcategory string, messageFormat string, parameters ...interface{})

	// LogMethodReturn sends a logging entry of MethodReturn log type for the given session associated to the session ID
	LogMethodReturn(returns ...interface{})

	// LogMethodExit sends a logging entry of MethodExit log type for the given session associated to the session ID
	LogMethodExit()
}

SessionLogging is a subset of Session interface, containing only logging related methods

type SessionMeta

type SessionMeta interface {
	// GetID returns the ID of this registered session object
	GetID() uuid.UUID

	// GetName returns the name registered to session object for given session ID
	GetName() string
}

SessionMeta is a subset of Session interface, containing only meta data related methods

type SessionWebcall

type SessionWebcall interface {
	// CreateWebcallRequest generates a webcall request object to the targeted external web service for the given session associated to the session ID
	CreateWebcallRequest(method string, url string, payload string, sendClientCert bool) WebRequest
}

SessionWebcall is a subset of Session interface, containing only webcall related methods

type Static

type Static struct {
	Name       string
	PathPrefix string
	Handler    http.Handler
}

Static holds the registration information of a static content hosting

type WebRequest

type WebRequest interface {
	// AddQuery adds a query to the request URL for sending through HTTP
	AddQuery(name string, value string) WebRequest
	// AddHeader adds a header to the request Header for sending through HTTP
	AddHeader(name string, value string) WebRequest
	// SetupRetry sets up automatic retry upon error of specific HTTP status codes; each entry maps an HTTP status code to how many times retry should happen if code matches
	SetupRetry(connectivityRetryCount int, httpStatusRetryCount map[int]int, retryDelay time.Duration) WebRequest
	// Anticipate registers a data template to be deserialized to when the given range of HTTP status codes are returned during the processing of the web request; latter registration overrides former when overlapping
	Anticipate(beginStatusCode int, endStatusCode int, dataTemplate interface{}) WebRequest
	// Process sends the webcall request over the wire, retrieves and serialize the response to registered data templates, and returns status code, header and error accordingly
	Process() (statusCode int, responseHeader http.Header, responseError error)
}

WebRequest is an interface for easy operating on webcall requests and responses

type WebRequestCustomization

type WebRequestCustomization interface {
	// ClientCert is to customize the client certificate for external requests; if not set or nil, no client certificate is sent to external web services
	ClientCert() *tls.Certificate

	// DefaultTimeout is to customize the default timeout for any webcall communications through HTTP/HTTPS by session
	DefaultTimeout() time.Duration

	// SkipServerCertVerification is to customize the skip of server certificate verification for any webcall communications through HTTP/HTTPS by session
	SkipServerCertVerification() bool

	// RoundTripper is to customize the creation of the HTTP transport for any webcall communications through HTTP/HTTPS by session
	RoundTripper(originalTransport http.RoundTripper) http.RoundTripper

	// WrapRequest is to customize the creation of the HTTP request for any webcall communications through HTTP/HTTPS by session; utilize this method if needed for new relic wrapping, etc.
	WrapRequest(session Session, httpRequest *http.Request) *http.Request
}

WebRequestCustomization holds customization methods related to web requests

Jump to

Keyboard shortcuts

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