rmhttp

package module
v5.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 24, 2025 License: MIT Imports: 14 Imported by: 0

README

rmhttp

Go Reference GitHub go.mod Go version GitHub Release Date GitHub commits since latest release Contributor Covenant

rmhttp provides a lightweight wrapper around the Go standard library HTTP server and router provided by net/http that allows for the easy addition of timeouts, groups, headers, and middleware (at the route, group and server level).

This package aims to make it easier to configure your routes and middleware, but then hand off as much as possible to the standard library once the server is running. Standard net/http handlers and middleware functions are used throughout.

Installation

Run the following command from your project root directory to install rmhttp into your project.

go get github.com/rmhubbert/rmhttp/v5

Quickstart

The following code will get you up and running quickly with a basic GET endpoint.

package main

import (
	"log"
	"net/http"

	"github.com/rmhubbert/rmhttp/v5"
)

func myHandler := func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Hello World"))
}

func main() {
    // New() creates and intialises the app. You can optionally pass
    // in a configuration object.
    rmh := rmhttp.New()

    // Handle(), HandleFunc(), Post(), Put(), Patch(), Delete() and
    // Options() methods are also available.
    rmh.Get("/hello", myHandler)

    // ListenAndServe() starts the server.
    log.Fatal(rmh.ListenAndServe())
}

Configuration

Configuration options can be set via environment variables or by passing in a Config object to the New() method, See https://github.com/rmhubbert/rmhttp/blob/main/config.go for details.

Usage

rmhttp offers a fluent interface for building out your server functionality, allowing you to easily customise your server, groups, and routes. Here are some simple examples of the core functionality to get you started.

Error Handling

You can register your own handlers for 404 and 405 errors. These errors are normally triggered internally by http.ServeMux, and are normally not configurable.

package main

import (
	"log"
	"net/http"

	"github.com/rmhubbert/rmhttp/v5"
)

func my404Handler := func(w http.ResponseWriter, r *http.Request) {
    http.Error(w, "My 404 Message", http.StatusNotFound)
}

func my405Handler := func(w http.ResponseWriter, r *http.Request) {
    http.Error(w, "My 405 Message", http.StatusMethodNotAllowed)
}

func main() {
    rmh := rmhttp.New()
    // This handler will replace the default 404 HTTP status code handler.
    rmh.StatusNotFoundHandler(my404Handler)

	// This handler will replace the default 405 HTTP status code handler.
    rmh.StatusMethodNotAllowedHandler(my405Handler)

    log.Fatal(rmh.ListenAndServe())
}
Groups

Routes can be easily grouped by registering them with a Group object. This allows all of the routes registered this way to inherit the group URL pattern plus any configured headers and middleware.

package main

import (
	"log"
	"net/http"

	"github.com/rmhubbert/rmhttp/v5"
)

func myHandler := func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Hello World"))
}

func main() {
    rmh := rmhttp.New()
    // The following creates a Group and then registers a Get route with that Group.
    // The route will be accessible at /api/hello.
    rmh.Group("/api").Get("/hello", myHandler)

    log.Fatal(rmh.ListenAndServe())
}
Headers

Headers can be easily added at the global, group, and route level by calling WithHeader() on the desired target.

package main

import (
	"log"
	"net/http"

	"github.com/rmhubbert/rmhttp/v5"
)

func myHandler := func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Hello World"))
}

func main() {
    rmh := rmhttp.New().WithHeader("X-Hello", "World")
    rmh.Get("/hello", myHandler).WithHeader("X-My", "Header")

    log.Fatal(rmh.ListenAndServe())
}
Timeouts

Timeouts can be easily added at the global, group, and route level by calling WithTimeout() on the desired target. The length of timeout is set in seconds.

package main

import (
	"log"
	"net/http"

	"github.com/rmhubbert/rmhttp/v5"
)

func myHandler := func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Hello World"))
}

func main() {
    rmh := rmhttp.New().WithTimeout(5, "Global timeout message")
    rmh.Get("/hello", myHandler).WithTimeout(3, "Route timeout message")

    log.Fatal(rmh.ListenAndServe())
}
Middleware

Middleware can be easily added at the global, group, and route level by calling WithMiddleware() or Use() on the desired target.

package main

import (
	"log"
	"net/http"

	"github.com/rmhubbert/rmhttp/v5"
	"github.com/rmhubbert/rmhttp/v5/pkg/middleware/recoverer"
)

func myHandler := func(w http.ResponseWriter, r *http.Request) {
    w.WriteHeader(http.StatusOK)
    w.Write([]byte("Hello World"))
}

func main() {
    rmh := rmhttp.New().WithMiddleware(recoverer.Middleware())
    rmh.Get("/hello", myHandler)

    log.Fatal(rmh.ListenAndServe())
}

License

rmhttp is made available for use via the MIT license.

Contributing

Contributions are always welcome via Pull Request. Please make sure to add tests and make sure they are passing before submitting. It's also a good idea to lint your code with golintci-lint, using the config in this directory.

Contributors are expected to abide by the guidelines outlined in the Contributor Covenant Code of Conduct

Documentation

Overview

Package rmhttp implements a lightweight wrapper around the standard library web server provided by http.Server and http.ServeMux, and adds an intuitive fluent interface for easy use and configuration of route grouping, logging, CORS, panic recovery, header management, timeouts, and middleware.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func TimeoutMiddleware

func TimeoutMiddleware(timeout Timeout) func(http.Handler) http.Handler

TimeoutMiddleware creates, initialises and returns a middleware function that will wrap the next handler in the stack with a timeout handler.

func ValidHTTPMethods

func ValidHTTPMethods() []string

ValidHTTPMethods returns a slice of strings containing all of the HTTP methods that rmhttp will accept.

Types

type App

type App struct {
	Server *Server
	Router *Router
	// contains filtered or unexported fields
}

App encapsulates the application and provides the public API, as well as orchestrating the core library functionality.

func New

func New(c ...Config) *App

New creates, initialises and returns a pointer to a new App. An optional configuration can be passed to configure many parts of the system, such as cors, SSL, and timeouts.

If you chose not to pass in a configuration, rmhttp will first attempt to load configuration values from environment variables, and if they're not found, will apply sensible defaults.

func (*App) Compile

func (app *App) Compile()

Compile prepares the app for starting by applying the middleware, and loading the Routes. It should be the last function to be called before starting the Server.

func (*App) Delete

func (app *App) Delete(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Route

Delete binds the passed handler to the specified route pattern for DELETE requests.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) Get

func (app *App) Get(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Route

Get binds the passed handler to the specified route pattern for GET requests.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) Group

func (app *App) Group(pattern string) *Group

Group creates, initialises, and returns a pointer to a Route Group.

This is typically used to create new Routes as part of the Group, but can also be used to add Group specific middleware, timeouts, etc.

This method will return a pointer to the new Group, allowing the user to chain any of the other builder methods that Group implements.

func (*App) Handle

func (app *App) Handle(method string, pattern string, handler http.Handler) *Route

Handle binds the passed http.Handler to the specified route method and pattern.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) HandleFunc

func (app *App) HandleFunc(
	method string,
	pattern string,
	handlerFunc http.HandlerFunc,
) *Route

HandleFunc binds the passed http.HandlerFunc to the specified route method and pattern.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) ListenAndServe

func (app *App) ListenAndServe() error

ListenAndServe compiles and loads the registered Routes, and then starts the Server without SSL.

func (*App) ListenAndServeTLS

func (app *App) ListenAndServeTLS(cert string, key string) error

ListenAndServeTLS compiles and loads the registered Routes, and then starts the Server with the SSL certificate and key at the file paths passed as the arguments.

func (*App) Options

func (app *App) Options(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Route

Options binds the passed handler to the specified route pattern for OPTIONS requests.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) Patch

func (app *App) Patch(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Route

Patch binds the passed handler to the specified route pattern for PATCH requests.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) Post

func (app *App) Post(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Route

Post binds the passed handler to the specified route pattern for POST requests.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) Put

func (app *App) Put(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Route

Put binds the passed handler to the specified route pattern for PUT requests.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) Redirect

func (app *App) Redirect(pattern string, target string, code int) *Route

Redirect creates and binds a redirect handler to the specified pattern for GET requests.

A temporary redirect status code will be used if the passed code is not in the 300 - 308 range.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) Route

func (app *App) Route(route *Route)

Route adds a Route to the application at the top level.

This allows us to overwrite Routes prior to application start without causing the underlying http.ServeMux to throw an error.

func (*App) Routes

func (app *App) Routes() map[string]*Route

Routes returns a map of the currently added Routes.

func (*App) Shutdown

func (app *App) Shutdown(ctx context.Context) error

Shutdown stops the Server.

func (*App) Static

func (app *App) Static(pattern string, targetDir string) *Route

Static creates and binds a filesystem handler to the specified pattern for GET requests.

If the pattern contains a trailing slash, the filesystem handler may not behave as expected.

This method will return a pointer to the new Route, allowing the user to chain any of the other builder methods that Route implements.

func (*App) StatusMethodNotAllowedHandler

func (app *App) StatusMethodNotAllowedHandler(
	handler http.HandlerFunc,
)

StatusMethodNotAllowedHandler registers a handler to be used when an internal 405 error is thrown.

func (*App) StatusNotFoundHandler

func (app *App) StatusNotFoundHandler(handler http.HandlerFunc)

StatusNotFoundHandler registers a handler to be used when an internal 404 error is thrown.

func (*App) Use

func (app *App) Use(middlewares ...func(http.Handler) http.Handler) *App

Use is a convenience method for adding global middleware handlers. It uses WithMiddleware behind the scenes.

This method will return a pointer to the app, allowing the user to chain any of the other builder methods that the app implements.

func (*App) WithHeader

func (app *App) WithHeader(key string, value string) *App

WithHeader adds an HTTP header at the global level. Calling this method more than once with the same key will overwrite the existing header.

This method will return a pointer to the app, allowing the user to chain any of the other builder methods that the app implements.

func (*App) WithMiddleware

func (app *App) WithMiddleware(middlewares ...func(http.Handler) http.Handler) *App

WithMiddleware is a convenience method for adding global middleware handlers.

This method will return a pointer to the app, allowing the user to chain any of the other builder methods that the app implements.

func (*App) WithTimeout

func (app *App) WithTimeout(timeout time.Duration, message string) *App

WithTimeout sets a request timeout amount and message at the global level.

This method will return a pointer to the app, allowing the user to chain any of the other builder methods that the app implements.

type CaptureWriter

type CaptureWriter struct {
	Writer      http.ResponseWriter
	Code        int
	Body        string
	Mu          sync.Mutex
	PassThrough bool
}

A CaptureWriter wraps a http.ResponseWriter in order to capture HTTP the response code & body that handlers will set. We do this to allow reading these values after they have been set, as this is not normally possible on a ResponseWriter.

func NewCaptureWriter

func NewCaptureWriter(w http.ResponseWriter) *CaptureWriter

New creates, instantiates, and returns a new CaptureWriter.

func (*CaptureWriter) Flush

func (cw *CaptureWriter) Flush()

Flush implements the Flusher interface.

func (*CaptureWriter) Header

func (cw *CaptureWriter) Header() http.Header

Header implements part of the http.ResponseWriter interface. We simply pass this to the underlying ResponseWriter, as you can already retrieve a Header from that.

func (*CaptureWriter) Hijack

func (cw *CaptureWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements the Hijacker interface.

func (*CaptureWriter) Push

func (cw *CaptureWriter) Push(target string, opts *http.PushOptions) error

Push implements the Pusher interface.

func (*CaptureWriter) Unwrap

func (cw *CaptureWriter) Unwrap() http.ResponseWriter

Unwrap returns the underlying http.ResponseWriter. It is used internally by http.ResponseController, which allows you to use custom http.ResponseWriter instances more easily.

func (*CaptureWriter) Write

func (cw *CaptureWriter) Write(body []byte) (int, error)

Write implements part of the http.ResponseWriter interface. We override it here in order to store the response body, before optionally writing to the underlying ResponseWriter.

func (*CaptureWriter) WriteHeader

func (cw *CaptureWriter) WriteHeader(code int)

WriteHeader implements part of the http.ResponseWriter interface. We override it here in order to store the response code, before optionally writing to the underlying ResponseWriter.

type Config

type Config struct {
	Debug  bool `env:"DEBUG"`
	Server ServerConfig
}

The Config contains settings (with defaults) for configuring the app, server and router.

func LoadConfig

func LoadConfig(cfg Config) (Config, error)

loadConfig parses the environment variables defined in the Config objects (with defaults), then merges those with the config that the user may have supplied. This function only gets called during app initialisation.

This function will return a completed config, or error if the environment variables cannot be parsed.

type Group

type Group struct {
	Pattern    string
	Middleware []func(http.Handler) http.Handler
	Timeout    Timeout
	Headers    map[string]string
	Parent     *Group
	Routes     map[string]*Route
	Groups     map[string]*Group
}

A Group allows for grouping sub groups or routes under a route prefix. It also enables you to add headers, timeout and middleware once to every sub group and route included in the group.

func NewGroup

func NewGroup(pattern string) *Group

NewGroup creates, initialises, and returns a pointer to a new Group

func (*Group) ComputedRoutes

func (group *Group) ComputedRoutes() map[string]*Route

ComputedRoutes returns a map of unique Routes composed from this Group and any sub Groups of this Group.

func (*Group) Delete

func (group *Group) Delete(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Group

Delete binds the passed handler to the specified route pattern for DELETE requests.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) Get

func (group *Group) Get(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Group

Get binds the passed handler to the specified route pattern for GET requests.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) Group

func (group *Group) Group(g *Group) *Group

Group adds the passed Group as a sub group to this Group.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) Handle

func (group *Group) Handle(method string, pattern string, handler http.Handler) *Group

Handle binds the passed rmhttp.Handler to the specified route method and pattern.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) HandleFunc

func (group *Group) HandleFunc(
	method string,
	pattern string,
	handlerFunc http.HandlerFunc,
) *Group

HandleFunc converts the passed handler function to a rmhttp.HandlerFunc, and then binds it to the specified route method and pattern.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) Options

func (group *Group) Options(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Group

Options binds the passed handler to the specified route pattern for OPTIONS requests.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) Patch

func (group *Group) Patch(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Group

Patch binds the passed handler to the specified route pattern for PATCH requests.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) Post

func (group *Group) Post(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Group

Post binds the passed handler to the specified route pattern for POST requests.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) Put

func (group *Group) Put(
	pattern string,
	handlerFunc http.HandlerFunc,
) *Group

Put binds the passed handler to the specified route pattern for PUT requests.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) Route

func (group *Group) Route(route *Route) *Group

Route adds the passed Route to this Group.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) Use

func (group *Group) Use(middlewares ...func(http.Handler) http.Handler) *Group

Use is a convenience method for adding middleware handlers to a Group. It uses WithMiddleware behind the scenes.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) WithHeader

func (group *Group) WithHeader(key, value string) *Group

WithHeader sets an HTTP header for this Group. Calling this method with the same key more than once will overwrite the existing header.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) WithMiddleware

func (group *Group) WithMiddleware(middlewares ...func(http.Handler) http.Handler) *Group

WithMiddleware adds Middleware handlers to the receiver Group.

Each middleware handler will be wrapped to create a call stack with the order in which the middleware is added being maintained. So, for example, if the user added A and B middleware via this method, the resulting callstack would be as follows -

Middleware A -> Middleware B -> Route Handler -> Middleware B -> Middleware A

(This actually a slight simplification, as internal middleware such as HTTP Logging, CORS, HTTP Error Handling and Route Panic Recovery may also be inserted into the call stack, depending on how the App is configured).

The middlewares argument is variadic, allowing the user to add multiple middleware functions in a single call.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

func (*Group) WithTimeout

func (group *Group) WithTimeout(timeout time.Duration, message string) *Group

WithTimeout sets a request timeout amount and message for this Group.

This method will return a pointer to the receiver Group, allowing the user to chain any of the other builder methods that Group implements.

type HTTPError

type HTTPError struct {
	Err  error
	Code int
}

An HTTPError represents an error with an additional HTTP status code

func NewHTTPError

func NewHTTPError(err error, code int) HTTPError

NewHTTPError creates and returns a new, initialised pointer to a HTTPError

func (HTTPError) Error

func (e HTTPError) Error() string

Error returns the error text of the receiver HTTPError as a string.

This method allows HTTPError to implement the standard library Error interface.

func (HTTPError) Unwrap

func (e HTTPError) Unwrap() error

Unwrap returns the underlying Error that this HTTPError wraps.

This method allows an HTTPError to be used by errors.Is().

type Route

type Route struct {
	Method     string
	Pattern    string
	Handler    http.Handler
	Middleware []func(http.Handler) http.Handler
	Timeout    Timeout
	Headers    map[string]string
	Parent     *Group
}

A Route encapsulates all of the information that the router will need to satisfy an HTTP request. Alongside supplying standard information such as what HTTP method and URL pattern a handler should be bound to, the Route also allows the enclosed handler to be configured with their own timeout, headers, and middleware.

func NewRoute

func NewRoute(method string, pattern string, handler http.Handler) *Route

NewRoute validates the input, then creates, initialises and returns a pointer to a Route. The validation step ensures that a valid HTTP method has been passed (http.MethodGet will be used, if not). The method will also be transformed to uppercase, and the pattern to lowercase.

func (*Route) ComputedHeaders

func (route *Route) ComputedHeaders() map[string]string

ComputedHeaders dynamically calculates the HTTP headers that have been added to the Route and any parent Groups.

func (*Route) ComputedMiddleware

func (route *Route) ComputedMiddleware() []func(http.Handler) http.Handler

Middleware returns the slice of MiddlewareFuncs that have been added to the Route.

func (*Route) ComputedPattern

func (route *Route) ComputedPattern() string

ComputedPattern dynamically calculates the pattern for the Route. It returns the URL pattern as a string.

func (*Route) ComputedTimeout

func (route *Route) ComputedTimeout() Timeout

Timeout returns the Timeout object that has been added to the Route.

func (*Route) String

func (route *Route) String() string

String is used internally to calculate a string signature for use as map keys, etc.

func (*Route) Use

func (route *Route) Use(middlewares ...func(http.Handler) http.Handler) *Route

Use is a convenience method for adding middleware handlers to a Route. It uses WithMiddleware behind the scenes.

This method will return a pointer to the receiver Route, allowing the user to chain any of the other builder methods that Route implements.

func (*Route) WithHeader

func (route *Route) WithHeader(key, value string) *Route

WithHeader sets an HTTP header for this Route. Calling this method with the same key more than once will overwrite the existing header.

This method will return a pointer to the receiver Route, allowing the user to chain any of the other builder methods that Route implements.

func (*Route) WithMiddleware

func (route *Route) WithMiddleware(middlewares ...func(http.Handler) http.Handler) *Route

WithMiddleware adds Middleware handlers to the receiver Route.

Each middleware handler will be wrapped to create a call stack with the order in which the middleware is added being maintained. So, for example, if the user added A and B middleware via this method, the resulting callstack would be as follows -

Middleware A -> Middleware B -> Route Handler -> Middleware B -> Middleware A

(This actually a slight simplification, as internal middleware such as HTTP Logging, CORS, HTTP Error Handling and Route Panic Recovery may also be inserted into the call stack, depending on how the App is configured).

The middlewares argument is variadic, allowing the user to add multiple middleware functions in a single call.

This method will return a pointer to the receiver Route, allowing the user to chain any of the other builder methods that Route implements.

func (*Route) WithTimeout

func (route *Route) WithTimeout(timeout time.Duration, message string) *Route

WithTimeout sets a request timeout amount and message for this route.

This method will return a pointer to the receiver Route, allowing the user to chain any of the other builder methods that Route implements.

type Router

type Router struct {
	Mux *http.ServeMux
	// contains filtered or unexported fields
}

The Router loads Routes into the underlying HTTP request multiplexer, as well as handling each request, ensuring that ResponseWriter and Request objects are properly configured. The Router also manages custom error handlers to ensure that the HTTP Error Handler can operate properly.

func NewRouter

func NewRouter() *Router

NewRouter intialises, creates, and then returns a pointer to a Router.

func (*Router) AddErrorHandler

func (rt *Router) AddErrorHandler(code int, handler http.Handler)

AddErrorHandler maps the passed response code and handler. These error handlers will be used instead of the http.Handler equivalents when available.

func (*Router) Handle

func (rt *Router) Handle(method string, pattern string, handler http.Handler)

Handle registers the passed Route with the underlying HTTP request multiplexer.

func (*Router) ServeHTTP

func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP allows the Router to fulfill the http.Handler interface, meaning that we can use it as a handler for the underlying HTTP request multiplexer (which by default is a http.ServeMux).

We also intercept any error handlers returned by the underlying mux, and replace them with any custom error handlers that have been registered.

type Server

type Server struct {
	Server http.Server
	Router http.Handler
	Port   int
	Host   string
	// contains filtered or unexported fields
}

A Server wraps the standard library net/http.Server. It provide default lifecycle management and debugger logging on top of the expected http.Server behaviour.

func NewServer

func NewServer(
	config ServerConfig,
	router http.Handler,
) *Server

NewServer creates, initialises and returns a pointer to a Server.

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

ListenAndServe directly proxies the http.Server.ListenAndServe method. It starts the server without TLS support on the configured address and port.

func (*Server) ListenAndServeTLS

func (srv *Server) ListenAndServeTLS(cert string, key string) error

ListenAndServeTLS directly proxies the http.Server.ListenAndServeTLS method. It starts the server with TLS support on the configured address and port.

func (*Server) Shutdown

func (srv *Server) Shutdown(ctx context.Context) error

Shutdown directly proxies the net/http.Server.Shutdown method. It will stop the Server, if running.

type ServerConfig

type ServerConfig struct {
	TCPReadTimeout               int    `env:"TCP_READ_TIMEOUT"          envDefault:"2"`
	TCPReadHeaderTimeout         int    `env:"TCP_READ_HEADER_TIMEOUT"   envDefault:"1"`
	TCPIdleTimeout               int    `env:"TCP_IDLE_TIMEOUT"          envDefault:"120"`
	TCPWriteTimeout              int    `env:"TCP_WRITE_TIMEOUT"         envDefault:"5"`
	TCPWriteTimeoutPadding       int    `env:"TCP_WRITE_TIMEOUT_PADDING" envDefault:"1"`
	RequestTimeout               int    `env:"HTTP_REQUEST_TIMEOUT"      envDefault:"5"`
	TimeoutMessage               string `env:"HTTP_TIMEOUT_MESSAGE"      envDefault:"Request Timeout"`
	MaxHeaderBytes               int    `env:"HTTP_MAX_HEADER_BYTES"`
	Host                         string `env:"HOST"`
	Port                         int    `env:"PORT"                      envDefault:"8080"`
	DisableGeneralOptionsHandler bool
	TLSConfig                    *tls.Config
	TLSNextProto                 map[string]func(*http.Server, *tls.Conn, http.Handler)
	ConnState                    func(net.Conn, http.ConnState)
	ErrorLog                     *log.Logger
	BaseContext                  func(net.Listener) context.Context
	ConnContext                  func(ctx context.Context, c net.Conn) context.Context
	HTTP2                        *http.HTTP2Config
	Protocols                    *http.Protocols
}

The ServerConfig contains settings (with defaults) for configuring the underlying http.Server, as well as some additional timeout related properties. The server properties correlate to those found at https://pkg.go.dev/net/http#Server.

type Timeout

type Timeout struct {
	Duration time.Duration
	Message  string
	Enabled  bool
}

Timeout encapsulates a duration and message that should be used for applying timeouts to Route handlers, with a specific error message.

func NewTimeout

func NewTimeout(duration time.Duration, message string) Timeout

NewTimeout creates, initialises and returns a pointer to a Timeout.

Directories

Path Synopsis
pkg

Jump to

Keyboard shortcuts

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