web

package
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Dec 16, 2025 License: BSD-3-Clause Imports: 30 Imported by: 0

Documentation

Overview

Package web provides a configurable HTTP web server with built-in support for common middleware patterns, file serving, and WebSocket handling.

This package offers a singleton Server instance that can be customized through fluent-style methods for setting host, port, headers, middleware, handlers, and WebSocket routes.

Features include:

  • Serving static files from embedded file systems
  • Middleware support including security headers, CORS, gzip compression, and request logging
  • Easy registration of HTTP handlers and handler functions
  • WebSocket support with connection management and custom handlers
  • Multi-port support with HTTP and HTTPS protocols
  • Configurable redirect rules between ports and routes
  • Graceful shutdown and restart capabilities

Example usage:

package main

import (

"net/http"

"github.com/valentin-kaiser/go-core/web"

)

func main() {
	done := make(chan error)
	web.Instance().
		WithHost("localhost").
		WithHTTPPort(8080).
		WithHTTPSPort(8443).
		WithSelfSignedTLS().
		Redirect(8080, 8443, "/", "/").  // Redirect HTTP root to HTTPS
		WithSecurityHeaders().
		WithCORSHeaders().
		WithGzip().
		WithLog().
		WithHandlerFunc("/", handler).
		StartAsync(done)

	if err := <-done; err != nil {
		panic(err)
	}

	err := web.Instance().Stop()
	if err != nil {
		panic(err)
	}
}

func handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain")
	w.Write([]byte("Hello, World!"))
}

Index

Constants

This section is empty.

Variables

ErrorCodes contains a list of HTTP status codes that are considered errors.

Functions

This section is empty.

Types

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware is a function that takes an http.Handler and returns an http.Handler.

type MiddlewareOrder

type MiddlewareOrder int8

MiddlewareOrder defines the order in which middlewares are executed.

const (
	// MiddlewareOrderDefault is the default execution order for middlewares.
	// It is invoked at the same level as the original handler.
	MiddlewareOrderDefault MiddlewareOrder = 0
	// MiddlewareOrderLow represents the lowest execution order.
	// Middlewares with negative values (-128 to -1) are called before the original handler.
	MiddlewareOrderLow MiddlewareOrder = -128
	// MiddlewareOrderHigh represents the highest execution order.
	// Middlewares with positive values (1 to 127) are called after the original handler.
	MiddlewareOrderHigh MiddlewareOrder = 127
	// MiddlewareOrderSecurity is a specific order typically used for security-related middlewares.
	// It is called before the handler.
	MiddlewareOrderSecurity MiddlewareOrder = -127
	// MiddlewareOrderCors is a specific order typically used for CORS-related middlewares.
	// It is called before the handler.
	MiddlewareOrderCors MiddlewareOrder = -126
	// MiddlewareOrderLog is a specific order typically used for logging middlewares.
	// It is called after the handler.
	MiddlewareOrderLog MiddlewareOrder = 126
	// MiddlewareOrderGzip is a specific order typically used for gzip compression middlewares.
	MiddlewareOrderGzip MiddlewareOrder = 127
)

type Protocol added in v1.6.0

type Protocol string

Protocol represents the protocol type for a server port

const (
	// ProtocolHTTP represents HTTP protocol
	ProtocolHTTP Protocol = "http"
	// ProtocolHTTPS represents HTTPS protocol
	ProtocolHTTPS Protocol = "https"
)

type RedirectRule added in v1.6.0

type RedirectRule struct {
	SourcePort  uint16
	TargetPort  uint16
	SourceRoute string
	TargetRoute string
	Code        int                        // HTTP status code for the redirect
	Exceptions  []string                   // List of paths that should not be redirected
	Conditions  []func(*http.Request) bool // List of conditions that must be met for the redirect to occur
}

RedirectRule represents a redirect configuration

type ResponseWriter

type ResponseWriter struct {
	// contains filtered or unexported fields
}

ResponseWriter is a wrapper around http.ResponseWriter that captures the status code

func (*ResponseWriter) Header

func (rw *ResponseWriter) Header() http.Header

Header returns the custom header map

func (*ResponseWriter) Hijack

func (rw *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack is a wrapper around the http.Hijacker interface

func (*ResponseWriter) History

func (rw *ResponseWriter) History() [][]byte

History returns the history of response bodies written

func (*ResponseWriter) Status

func (rw *ResponseWriter) Status() int

Status returns the status code of the response

func (*ResponseWriter) Write

func (rw *ResponseWriter) Write(b []byte) (int, error)

Write buffers the response body

func (*ResponseWriter) WriteHeader

func (rw *ResponseWriter) WriteHeader(status int)

WriteHeader captures the status code but does not send it immediately It is send when Flush is called

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router is a custom HTTP router that supports middlewares and status callbacks It implements the http.Handler interface and allows for flexible request handling

func NewRouter

func NewRouter() *Router

NewRouter creates a new Router instance It initializes the ServeMux and the middlewares map

func (*Router) GetRegisteredRoutes

func (router *Router) GetRegisteredRoutes() []string

GetRegisteredRoutes returns a slice of all currently registered route patterns

func (*Router) Handle

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

Handle registers a handler for the given pattern

func (*Router) HandleFunc

func (router *Router) HandleFunc(pattern string, handlerFunc http.HandlerFunc)

HandleFunc registers a handler function for the given pattern

func (*Router) OnStatus

func (router *Router) OnStatus(pattern string, status int, fn func(http.ResponseWriter, *http.Request))

OnStatus registers a callback function for a specific HTTP status code This function will be called after the response is written if the status and pattern match It allows you to handle specific status codes, such as logging or a custom response

func (*Router) ServeHTTP

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

ServeHTTP implements the http.Handler interface for the Router It wraps the request with middlewares and handles the response

func (*Router) UnregisterAllHandler

func (router *Router) UnregisterAllHandler()

UnregisterAllHandler removes all routes from the router It clears all route-related maps and creates a new empty ServeMux

func (*Router) UnregisterHandler

func (router *Router) UnregisterHandler(patterns []string)

UnregisterHandler removes routes from the router It removes the route pattern from all relevant internal maps and recreates the ServeMux

func (*Router) Use

func (router *Router) Use(order MiddlewareOrder, middleware func(http.Handler) http.Handler)

Use adds a middleware to the router It allows you to specify the order of execution using MiddlewareOrder All middlewares of the same order will be executed in the order they were added

type Server

type Server struct {
	// Error is the error that occurred during the server's operation
	// It will be nil if no error occurred
	Error error
	// contains filtered or unexported fields
}

Server represents a web server with a set of middlewares and handlers

func Instance

func Instance() *Server

Instance returns the singleton instance of the web server

func New

func New() *Server

New creates a new singleton instance of the web server

func (*Server) GetRegisteredRoutes

func (s *Server) GetRegisteredRoutes() []string

GetRegisteredRoutes returns a slice of all currently registered route patterns

func (*Server) Redirect added in v1.6.0

func (s *Server) Redirect(sourcePort uint16, targetPort uint16, sourceRoute string, targetRoute string) *Server

Redirect adds a redirect rule from source port/route to target port/route (convenience method)

func (*Server) Restart

func (s *Server) Restart() error

Restart gracefully shuts down the web server and starts it again It will wait for all active connections to finish before shutting down

func (*Server) RestartAsync

func (s *Server) RestartAsync(done chan error)

RestartAsync gracefully shuts down the web server and starts it again asynchronously It will wait for all active connections to finish before shutting down

func (*Server) SetBlacklist

func (s *Server) SetBlacklist(list []string) *Server

SetBlacklist registers a blacklist for the server Addresses in the blacklist will be blocked from accessing the server This is useful for blocking known malicious IPs or ranges

func (*Server) SetWhitelist

func (s *Server) SetWhitelist(list []string) *Server

SetWhitelist registers a whitelist for the server Addresses in the whitelist will be ignored by the rate limit and honey pot

func (*Server) Shutdown

func (s *Server) Shutdown() error

Shutdown gracefully shuts down the web server It will wait for all active connections to finish before shutting down Make sure the program doesn't exit and waits instead for Shutdown to return

func (*Server) Start

func (s *Server) Start() *Server

Start starts the web server All middlewares and handlers that should be registered must be registered before calling this function

func (*Server) StartAsync

func (s *Server) StartAsync(done chan error)

StartAsync starts the web server asynchronously It will return immediately and the server will run in the background

func (*Server) Stop

func (s *Server) Stop() error

Stop stops the web server Close does not attempt to close any hijacked connections, such as WebSockets.

func (*Server) UnregisterAllHandler

func (s *Server) UnregisterAllHandler() *Server

UnregisterAllHandler removes all handlers from the server

func (*Server) UnregisterHandler

func (s *Server) UnregisterHandler(paths []string) *Server

UnregisterHandler removes multiple handlers from the server

func (*Server) WithCORSHeaders

func (s *Server) WithCORSHeaders() *Server

WithCORSHeaders adds CORS headers to the server

func (*Server) WithCacheControl

func (s *Server) WithCacheControl(cacheControl string) *Server

WithCacheControl sets a custom Cache-Control header value that will override the default cache control setting in security headers

func (*Server) WithCanonicalRedirect

func (s *Server) WithCanonicalRedirect(domain string) *Server

WithCanonicalRedirect sets a canonical redirect domain for the server If a request is made to the server with a different domain, it will be redirected to the canonical domain This is useful for SEO purposes and to avoid duplicate content issues

func (*Server) WithCustomErrorLog

func (s *Server) WithCustomErrorLog(logger *l.Logger) *Server

WithCustomErrorLog sets the error log for the server

func (*Server) WithCustomMiddleware

func (s *Server) WithCustomMiddleware(middleware Middleware) *Server

WithCustomMiddleware adds a custom middleware to the server

func (*Server) WithCustomMiddlewareOrder

func (s *Server) WithCustomMiddlewareOrder(order MiddlewareOrder, middleware Middleware) *Server

WithCustomMiddlewareOrder adds a custom middleware to the server with a specific order The order is a int8 value that determines the order of the middleware 0 is the original handler, -128 is the beginning of the chain, and 127 is the end of the chain

func (*Server) WithErrorLog

func (s *Server) WithErrorLog() *Server

WithErrorLog sets the default error log for the server It will log errors at the Error level using the zerolog logger

func (*Server) WithFS

func (s *Server) WithFS(entrypoints []string, filesystem fs.FS) *Server

WithFS serves files from the specified filesystem It will return an error in the Error field if the entrypoint is already registered as a handler or a websocket

func (*Server) WithFileServer

func (s *Server) WithFileServer(entrypoints []string, path string) *Server

WithFileServer serves files from the specified directory It will fail if the directory does not exist

func (*Server) WithGzip

func (s *Server) WithGzip() *Server

WithGzip enables gzip compression for the server

func (*Server) WithGzipLevel

func (s *Server) WithGzipLevel(level int) *Server

WithGzipLevel enables gzip compression with a specific level for the server

func (*Server) WithHTTPPort added in v1.6.0

func (s *Server) WithHTTPPort(port uint16) *Server

WithHTTPPort adds an HTTP port to the server (convenience method)

func (*Server) WithHTTPSPort added in v1.6.0

func (s *Server) WithHTTPSPort(port uint16) *Server

WithHTTPSPort adds an HTTPS port to the server (convenience method)

func (*Server) WithHandler

func (s *Server) WithHandler(path string, handler http.Handler) *Server

WithHandler adds a custom handler to the server It will return an error in the Error field if the path is already registered as a handler or a websocket

func (*Server) WithHandlerFunc

func (s *Server) WithHandlerFunc(path string, handler http.HandlerFunc) *Server

WithHandlerFunc adds a custom handler function to the server It will return an error in the Error field if the path is already registered as a handler or a websocket

func (*Server) WithHeader

func (s *Server) WithHeader(key, value string) *Server

WithHeader adds a custom header to the server

func (*Server) WithHeaders

func (s *Server) WithHeaders(headers map[string]string) *Server

WithHeaders adds multiple custom headers to the server

func (*Server) WithHoneypot

func (s *Server) WithHoneypot(pattern string) *Server

WithHoneypot registers a handler for the given pattern Clients that access this pattern will be blocked This is useful for detecting and blocking malicious bots or crawlers

func (*Server) WithHost

func (s *Server) WithHost(address string) *Server

WithHost sets the address of the web server

func (*Server) WithIdleTimeout

func (s *Server) WithIdleTimeout(timeout time.Duration) *Server

WithIdleTimeout sets the idle timeout for the server It will be used for all requests and connections

func (*Server) WithJRPC

func (s *Server) WithJRPC(path string, service *jrpc.Service) *Server

WithJRPC adds a JSON-RPC service handler to the server It will return an error in the Error field if the path is already registered as a handler or a websocket The service will be accessible at path/{service}/{method}

func (*Server) WithLog

func (s *Server) WithLog() *Server

WithLog adds a logging middleware to the server

func (*Server) WithOnHTTPCode

func (s *Server) WithOnHTTPCode(code int, pattern []string, handler func(http.ResponseWriter, *http.Request)) *Server

WithOnHTTPCode adds a custom handler for a specific HTTP status code and pattern. It will be called after the request is handled and before the response is sent, and is called with the http.ResponseWriter and the http.Request

func (*Server) WithOnHoneypot

func (s *Server) WithOnHoneypot(callback func(map[string]*net.IPNet)) *Server

WithOnHoneypot registers a callback function that will be called when a honeypot is triggered The callback will receives the blocklist used. Useful for persisting the blocklist

func (*Server) WithPort

func (s *Server) WithPort(port uint16, protocol Protocol) *Server

WithPort adds a port with the specified protocol to the server This method can be called multiple times to configure multiple ports

func (*Server) WithRateLimit

func (s *Server) WithRateLimit(pattern string, count int, period time.Duration) *Server

WithRateLimit applies a rate limit to the given pattern The limiter allows `count` events per `period` duration Example: WithRateLimit("/api", 10, time.Minute) allows 10 requests per minute

func (*Server) WithReadHeaderTimeout

func (s *Server) WithReadHeaderTimeout(timeout time.Duration) *Server

WithReadHeaderTimeout sets the read header timeout for the server It will be used for all requests and connections

func (*Server) WithReadTimeout

func (s *Server) WithReadTimeout(timeout time.Duration) *Server

WithReadTimeout sets the read timeout for the server It will be used for all requests and connections

func (*Server) WithRedirect added in v1.6.0

func (s *Server) WithRedirect(rule RedirectRule) *Server

WithRedirect adds a redirect rule from source port/route to target port/route

func (*Server) WithSecurityHeaders

func (s *Server) WithSecurityHeaders() *Server

WithSecurityHeaders adds security headers to the server

func (*Server) WithSelfSignedTLS

func (s *Server) WithSelfSignedTLS() *Server

WithSelfSignedTLS generates a self-signed TLS certificate for the web server It will use the host set by WithHost as the common name for the certificate

func (*Server) WithTLS

func (s *Server) WithTLS(config *tls.Config) *Server

WithTLS sets the TLS configuration for the web server

func (*Server) WithVaryHeader

func (s *Server) WithVaryHeader(header string) *Server

WithVaryHeader adds a Vary header to the server The Vary header indicates which request headers a server uses when selecting the representation of a resource This is important for caching behavior and content negotiation

func (*Server) WithVaryHeaders

func (s *Server) WithVaryHeaders(headers []string) *Server

WithVaryHeaders adds multiple Vary headers to the server The headers will be properly combined with any existing Vary headers

func (*Server) WithWebsocket

func (s *Server) WithWebsocket(path string, handler func(http.ResponseWriter, *http.Request, *websocket.Conn)) *Server

WithWebsocket adds a websocket handler to the server It will return an error in the Error field if the path is already registered as a handler or a websocket The handler function will be called with the http.ResponseWriter, http.Request and *websocket.Conn and will be responsible for handling and closing the connection

func (*Server) WithWriteTimeout

func (s *Server) WithWriteTimeout(timeout time.Duration) *Server

WithWriteTimeout sets the write timeout for the server It will be used for all requests and connections

type ServerPort added in v1.6.0

type ServerPort struct {
	Port     uint16
	Protocol Protocol
}

ServerPort represents a port configuration with protocol

Directories

Path Synopsis
Package jrpc provides a JSON-RPC over HTTP and WebSocket implementation with Protocol Buffer support.
Package jrpc provides a JSON-RPC over HTTP and WebSocket implementation with Protocol Buffer support.

Jump to

Keyboard shortcuts

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