server

package
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: May 3, 2023 License: MIT Imports: 16 Imported by: 5

Documentation

Overview

Package server implements a minor extension of the standard http.Server.

The primary extensions of this implementation over the standard library are:

  1. Integration with the base EasyTLS package, to provide a standardized and simpler interface for configuring and utilizing TLS on an HTTP Server.

  2. Slightly easier interface for starting and stopping the server, registering routes and middlewares, and a small library of included middlewares for common use-cases.

  3. Plugin integration via the easy-tls/plugins package. Client/Server application design can be broken down with an easy enough plugin system, which this is intended to provide. The http.Handler registration process has been simplified in such a way as to allow programmatic registration of Routes by the use of SimpleHandlers. A Server module can easily expose the set of routes it services as an array of SimpleHandlers, which can be iterated over and registered.

Index

Constants

View Source
const (
	// DefaultServerAddr represents the default address to serve on,
	// should a value not be provided.
	DefaultServerAddr string = ":8080"
)

Variables

This section is empty.

Functions

func MethodNotAllowedHandler

func MethodNotAllowedHandler() http.Handler

MethodNotAllowedHandler represents the default function to call if the method used on the path has not been registered explicitly.

func MiddlewareDefaultLogger

func MiddlewareDefaultLogger(logger *log.Logger) func(http.Handler) http.Handler

MiddlewareDefaultLogger provides a simple logging middleware, to view incoming connections as they arrive and print a basic set of properties of the request.

func MiddlewareLimitConnectionRate

func MiddlewareLimitConnectionRate(OncePer time.Duration, Timeout time.Duration, logger *log.Logger) func(http.Handler) http.Handler

MiddlewareLimitConnectionRate will limit the rate at which the Server will process incoming requests. This will process no more than 1 request per OncePer. Verbose mode includes a log message when a request begins processing through this function. If the request is not processed within Timeout, a failed statusCode will be generated and sent back.

func MiddlewareLimitMaxConnections

func MiddlewareLimitMaxConnections(ConnectionLimit int, Timeout time.Duration, logger *log.Logger) func(http.Handler) http.Handler

MiddlewareLimitMaxConnections will provide a mechanism to strictly limit the maximum number of concurrent requests served. Verbose mode includes a log message when a request begins processing through this function. If the request is not processed within Timeout, a failed statusCode will be generated and sent back.

func NewDefaultRouter

func NewDefaultRouter() *mux.Router

NewDefaultRouter will create a new Router, based on the gorilla/mux implementation. This will pre-set the "trailing-slash" behaviour to not be pedantic, as well as initialzing the "Not-Found" and "Method-Not-Allowed" behaviours to simply return the corresponding status codes. These can be overridden if desired.

func NotFoundHandler

func NotFoundHandler() http.Handler

NotFoundHandler represents the default handler to use for a route that doesn't exist, or used as a mechanism to "remove" a route by replacing the existing http.Handler with this.

Types

type MiddlewareHandler

type MiddlewareHandler = func(http.Handler) http.Handler

MiddlewareHandler represents the Type which must be satisfied by any function to be used as a middleware function in the Server chain.

type QueryKeyValue

type QueryKeyValue struct {
	Key   string
	Value string
}

QueryKeyValue is a key-value pair used to register routes with URL Query parameters.

type SimpleHandler

type SimpleHandler struct {

	// The actual HTTP Handler to call when this is matched
	Handler http.Handler `json:"-"`

	// Optional: To allow for a route to only match on a specific host or host:port
	Host string `json:",omitempty"`

	// Required: The URL Path to match the handler on
	Path string `json:",omitempty"`

	// Optional: The set of methods this handler will be operated for
	Methods []string `json:",omitempty"`

	// Optional: The set of Key/Value URL Query strings which must match
	// in order for this handler to be called.
	// See the mux.Route.Queries() for more details on the form and shape
	// of these values.
	Queries []QueryKeyValue `json:",omitempty"`

	// Optional: An additional description of the route, to provide additional context
	// and understanding when displayed via the "/about" handler.
	Description string `json:",omitempty"`
}

SimpleHandler represents a simplification to the standard http handlerFuncs, allowing simpler registration and logging with Routers.

func AddPrefixToRoutes

func AddPrefixToRoutes(Prefix string, Handlers ...SimpleHandler) []SimpleHandler

AddPrefixToRoutes will assert that all routes have a given prefix

func NewSimpleHandler

func NewSimpleHandler(h http.Handler, Path string, Methods ...string) SimpleHandler

NewSimpleHandler will create and return a new SimpleHandler, ready to be used. This constructor does not include the ability to specify a host or query parameters both to keep the argument list small, and because these are substantially less common than the URL path and acceptable methods. See the SimpleHandler.AddQueries() and SimpleHandler.AddHost() functions to specify these properties.

func (*SimpleHandler) AddDescription

func (H *SimpleHandler) AddDescription(Description string)

AddDescription will add an optional description field to the handler, which will be shown alongside the match criteria on the "/about" handler.

func (*SimpleHandler) AddHost

func (H *SimpleHandler) AddHost(Host string)

AddHost will configure the handler to only match for a given host or host:port argument. See the rules for mux.Route.Host() for more details on the shape of the Host string.

func (*SimpleHandler) AddQueries

func (H *SimpleHandler) AddQueries(QueryPairs ...string) error

AddQueries will add the Key/Value pairs to the Handler to be included when registered with the server. See the rules for mux.Route.Queries() for more details on the shape of these QueryPairs.

type SimpleServer

type SimpleServer struct {

	// The actual http.Server implementation
	*http.Server
	// contains filtered or unexported fields
}

SimpleServer is the extension to the default http.Server this package provides.

func NewServerHTTP

func NewServerHTTP(Addr ...string) *SimpleServer

NewServerHTTP will create a new HTTP-only server which will serve on the specified IP:Port address. This has NO TLS settings enabled. The server returned from this function only has the default http.ServeMux as the Router, so should have a dedicated router registered.

The default address of ":8080" will be used if none is provided. Only the first string will be treated as the address.

func NewServerHTTPS

func NewServerHTTPS(TLS *easytls.TLSBundle, Addr ...string) (*SimpleServer, error)

NewServerHTTPS will create a new HTTPS-only server which will serve on the specified IP:Port address. The server returned from this function only has the default http.ServeMux as the Router, so should have a dedicated router registered. The default address of ":8080" will be used if none is provided

func (*SimpleServer) AddHandlers

func (S *SimpleServer) AddHandlers(Router *mux.Router, Handlers ...SimpleHandler)

AddHandlers will add the given handlers to the router, with the verbose flag determining if a log message should be generated for each added route.

func (*SimpleServer) AddMiddlewares

func (S *SimpleServer) AddMiddlewares(middlewares ...MiddlewareHandler)

AddMiddlewares is a convenience wrapper for the mux.Router "Use" function. This will add the middlewares to the router in the order specified, which also defines their execution order.

func (*SimpleServer) AddSubrouter

func (S *SimpleServer) AddSubrouter(Router *mux.Router, PathPrefix string, Handlers ...SimpleHandler)

AddSubrouter will add the set of Handlers to the server by creating a dedicated Subrouter of the given Router.

Currently, these subrouters are defined based on PathPrefix.

func (*SimpleServer) Addr

func (S *SimpleServer) Addr() string

Addr exposes the underlying local address of the SimpleServer.

func (*SimpleServer) CloneTLSConfig

func (S *SimpleServer) CloneTLSConfig() (*tls.Config, error)

CloneTLSConfig will form a proper clone of the underlying tls.Config.

func (*SimpleServer) ListenAndServe

func (S *SimpleServer) ListenAndServe() error

ListenAndServe will start the SimpleServer, serving HTTPS if enabled, or HTTP if not. This will properly wait for the shutdown to FINISH before returning.

func (*SimpleServer) Logger

func (S *SimpleServer) Logger() *log.Logger

Logger will return the internal logger used by the server.

func (*SimpleServer) RegisterSPAHandler

func (S *SimpleServer) RegisterSPAHandler(URLBase, PathBase string) error

RegisterSPAHandler will register an HTTP Handler to allow serving a Single Page Application. The application will be based off URLBase, and will serve content based out of PathBase.

The URLBase must be the same as what's defined to be <base href="/URLBase"> within the SPA.

This handler is fully able to be served on the same server as the raw API nodes, as long as the URLBase path is a distinct URL tree.

func (*SimpleServer) Router

func (S *SimpleServer) Router() *mux.Router

Router will return a pointer to the underlying router used by the server.

func (*SimpleServer) Serve

func (S *SimpleServer) Serve(l net.Listener) error

Serve will serve the SimpleServer at the given Listener, rather than allowing it to build its own set.

func (*SimpleServer) SetKeepAlives

func (S *SimpleServer) SetKeepAlives(SetTo bool)

SetKeepAlives will configure the server for whether or not it should use Keep-Alives. True implies to use Keep-Alives, and false will disable them.

func (*SimpleServer) SetLogger

func (S *SimpleServer) SetLogger(logger *log.Logger)

SetLogger will update the logger used by the server from the default to the given output.

func (*SimpleServer) SetTimeouts

func (S *SimpleServer) SetTimeouts(ReadTimeout, ReadHeaderTimeout, WriteTimeout, IdleTimeout, ShutdownTimeout time.Duration)

SetTimeouts will set the given timeouts of the Server. Set 0 to leave uninitialized.

func (*SimpleServer) Shutdown

func (S *SimpleServer) Shutdown() error

Shutdown will safely shut down the SimpleServer, returning any errors

func (*SimpleServer) TLSBundle

func (S *SimpleServer) TLSBundle() *easytls.TLSBundle

TLSBundle will return a copy of the underlying TLS Bundle

Directories

Path Synopsis
Package fileserver provides a set of SimpleHandlers to implement a simple file-system backed file server.
Package fileserver provides a set of SimpleHandlers to implement a simple file-system backed file server.

Jump to

Keyboard shortcuts

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