httpserver

package
v0.0.9 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2024 License: BSD-3-Clause Imports: 21 Imported by: 0

Documentation

Overview

Package httpserver extends the functionality of the standard library http.Server.

Key Features:

  • Manage routing paths, middleware registration, and handler registrations of the standard library http.Server.
  • Some built-in middleware.

ServeMux

ServeMux extends http.Handler designed to manage routing paths, middleware registration, and handler registrations of the standard library http.Server. It serves as a versatile routing mechanism that can handle middleware and nested routers efficiently.

Default behavior when registering a handler:

  • If no route was registered in '[HOST]/', register a handler for not found routes, inheriting the middleware stack (log HandlerNotFound).
  • If no route was registered in '[HOST]/[PATH]', register a handler for not allowed methods routes, inheriting the middleware stack (log HandlerMethodNotAllowed).
  • Then register the defined handler (log HandlerFn).

A variadic set of OptionServeMux used to configure the behavior of the ServeMux:

Methods for adding middleware:

  • [ServeMux.Use]: Appends one or more middlewares.
  • [ServeMux.With]: Appends one or more middlewares and register the Handle inline.

Methods for managing the routing path:

  • [ServeMux.Group]: Inline router manager, inheriting the middleware stack.
  • [ServeMux.Route]: Subrouter manager, inheriting the middleware stack.

Methods for registering an http handler:

  • [ServeMux.Connect]: Registers a handler for the HTTP CONNECT method.
  • [ServeMux.Delete]: Registers a handler for the HTTP DELETE method.
  • [ServeMux.Get]: Registers a handler for the HTTP GET method.
  • [ServeMux.Head]: Registers a handler for the HTTP HEAD method.
  • [ServeMux.Options]: Registers a handler for the HTTP OPTIONS method.
  • [ServeMux.Patch]: Registers a handler for the HTTP PATCH method.
  • [ServeMux.Post]: Registers a handler for the HTTP POST method.
  • [ServeMux.Put]: Registers a handler for the HTTP PUT method.
  • [ServeMux.Trace]: Registers a handler for the HTTP TRACE method.
  • [ServeMux.Method]: Registers a handler for the custom HTTP method.

Middlewares

  • MiddlewareLogging: Logs each incoming request along with useful metadata regarding the request.
  • MiddlewareTrace: Adds attributes to spans and metrics for telemetry purposes.
  • MiddlewareRecover: Recovers from panics, logs the panic, and responds with an HTTP status of 500 (Internal Server Error).

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func MiddlewareLogging added in v0.0.6

func MiddlewareLogging(next http.Handler) http.Handler

MiddlewareLogging is a middleware that logs each incoming request along with useful metadata regarding the request.

Response Status Handling:

  • Error: For response status < 100 and >= 500
  • Warn: For response status < 200 and >= 400
  • Info: Other response status

Log Identifier Handling:

  • If the X-Logger-ID header is present in the request, its value will be used as the log identifier.
  • If the header is not present or if the value is invalid, a new log identifier will be generated using UUID v7.
  • The log identifier is then added to the context logger.ContextLogID.

Log Level Handling:

  • If the X-Logger-Level header is present in the request, its value will be used as the minimum log level. Allowing lower priority logs at runtime.
  • The minimum log level is then added to the context logger.ContextMinLevel.

Important Note:

  • MiddlewareLogging should be positioned before any other middleware that may alter the response, such as MiddlewareRecover.
  • Must be used with logger.NewHandler to register the log handle and allow lower priority logging at runtime.

Example:

mux := httpserver.NewServeMux()
mux.Use(httpserver.MiddlewareLogging)   // <--<< MiddlewareLogging must come before MiddlewareRecover
mux.Use(httpserver.MiddlewareRecover)
mux.Get("/", handler)

func MiddlewareRecover added in v0.0.6

func MiddlewareRecover(next http.Handler) http.Handler

MiddlewareRecover is a middleware that recovers from panics, logs the panic, and responds with an HTTP status of 500 (Internal Server Error).

func MiddlewareTrace added in v0.0.9

func MiddlewareTrace(next http.Handler) http.Handler

MiddlewareTrace is a middleware that adds attributes to spans and metrics for telemetry purposes.

Adds telemetry attributes for monitoring:

  • attribute http.route: Indicates the pattern of the HTTP request used in spans and metrics.
  • attribute log.id: Log identifier associated with the request used in spans.
  • header Traceparent: Trace span associated with the request used in the response.

Important Note:

  • MiddlewareTrace should be placed after MiddlewareLogging middleware.
  • MiddlewareTrace should be positioned before any other middleware that may alter the response, such as MiddlewareRecover.

Example:

mux := httpserver.NewServeMux()
mux.Use(httpserver.MiddlewareLogging)
mux.Use(httpserver.MiddlewareTrace)   // <--<< MiddlewareTrace must come before MiddlewareRecover and after MiddlewareLogging
mux.Use(httpserver.MiddlewareRecover)
mux.Get("/", handler)

Types

type Handle

type Handle interface {
	// Connect registers a handler for the HTTP CONNECT method, under the current routing path plus the specified pattern.
	Connect(pattern string, handlerFn http.HandlerFunc)
	// Delete registers a handler for the HTTP DELETE method, under the current routing path plus the specified pattern.
	Delete(pattern string, handlerFn http.HandlerFunc)
	// Get registers a handler for the HTTP GET method, under the current routing path plus the specified pattern.
	Get(pattern string, handlerFn http.HandlerFunc)
	// Head registers a handler for the HTTP HEAD method, under the current routing path plus the specified pattern.
	Head(pattern string, handlerFn http.HandlerFunc)
	// Options registers a handler for the HTTP OPTIONS method, under the current routing path plus the specified pattern.
	Options(pattern string, handlerFn http.HandlerFunc)
	// Patch registers a handler for the HTTP PATCH method, under the current routing path plus the specified pattern.
	Patch(pattern string, handlerFn http.HandlerFunc)
	// Post registers a handler for the HTTP POST method, under the current routing path plus the specified pattern.
	Post(pattern string, handlerFn http.HandlerFunc)
	// Put registers a handler for the HTTP PUT method, under the current routing path plus the specified pattern.
	Put(pattern string, handlerFn http.HandlerFunc)
	// Trace registers a handler for the HTTP TRACE method, under the current routing path plus the specified pattern.
	Trace(pattern string, handlerFn http.HandlerFunc)
	// Method registers a handler for the custom HTTP method, under the current routing path plus the specified pattern.
	Method(method, pattern string, handlerFn http.HandlerFunc)
}

Handle interface allows the registration of HTTP handlers under the current routing path plus the specified pattern. It includes methods for each standard HTTP method.

type OptionCors added in v0.0.8

type OptionCors func(*cors)

OptionCors is used to apply configurations to a cors when creating it with WithCors.

func WithAllowCredentials added in v0.0.8

func WithAllowCredentials(allowCredentials bool) OptionCors

WithAllowCredentials is an OptionCors that allows credentials.

func WithAllowOriginFunc added in v0.0.8

func WithAllowOriginFunc(fn func(r *http.Request, origin string) bool) OptionCors

WithAllowOriginFunc is an OptionCors that defines a function to allow origin.

func WithAllowedHeaders added in v0.0.8

func WithAllowedHeaders(allowedHeaders ...string) OptionCors

WithAllowedHeaders is an OptionCors that defines the list of allowed headers.

func WithAllowedOrigins added in v0.0.8

func WithAllowedOrigins(allowedOrigins ...string) OptionCors

WithAllowedOrigins is an OptionCors that defines the list of allowed origins.

func WithCorsMaxAge added in v0.0.8

func WithCorsMaxAge(seconds int) OptionCors

WithCorsMaxAge is an OptionCors that defines a maximum age in seconds.

func WithExposedHeaders added in v0.0.8

func WithExposedHeaders(exposedHeaders ...string) OptionCors

WithExposedHeaders is an OptionCors that defines the list of exposed headers.

type OptionServeMux added in v0.0.8

type OptionServeMux func(*serveMux)

OptionServeMux is used to apply configurations to a ServeMux when creating it with NewServeMux.

func WithCors added in v0.0.8

func WithCors(opts ...OptionCors) OptionServeMux

WithCors is an OptionServeMux that defines information that will be used in the handlers for CORS processing. A variadic set of OptionCors used to configure CORS processing.

Default:

  • The default maximum age is 86400 seconds.

Default Behavior:

func WithHandlerMethodNotAllowed added in v0.0.9

func WithHandlerMethodNotAllowed(handlerFn http.HandlerFunc) OptionServeMux

WithHandlerMethodNotAllowed is an OptionServeMux that sets up a handler for not allowed methods routes. Inheriting the middleware stack.

Default Behavior without using Cors:

  • Automatically add the Allow in the response header.
  • Automatically add the Cache-Control in the response header. See WithHandlerOptionsMaxAge.

func WithHandlerNotFound added in v0.0.9

func WithHandlerNotFound(handlerFn http.HandlerFunc) OptionServeMux

WithHandlerNotFound is an OptionServeMux that sets up a handler for not found routes. Inheriting the middleware stack.

func WithHandlerOptionsMaxAge added in v0.0.9

func WithHandlerOptionsMaxAge(seconds int) OptionServeMux

TODO refatorar nome WithHandlerOptionsMaxAge is an OptionServeMux that defines in seconds the maximum age for the Cache-Control header response in the options method handlers.

Default:

  • The default maximum age for the Cache-Control header response is 86400 seconds.

type Router

type Router interface {
	Handle

	// Use appends one or more middlewares to the middleware stack for the Router in the current routing path.
	Use(middlewares ...func(http.Handler) http.Handler)
	// With appends one or more middlewares to the middleware stack in the current routing path to register the inline Handle.
	With(middlewares ...func(http.Handler) http.Handler) Handle
	// Group return a new inline Router under the current routing path plus the specified pattern, inheriting the middleware stack.
	Group(pattern string) Router
	// Route allowing additional routes to be defined within the subrouter under the current routing path plus the specified pattern, inheriting the middleware stack.
	Route(pattern string, fn func(subMux Router))
}

Router interface extends the Handle interface. It is designed to manage routing paths, middleware registration, and handler registrations.

type ServeMux

type ServeMux interface {
	Router
	http.Handler
}

ServeMux extends http.Handler designed to manage routing paths, middleware registration, and handler registrations of the standard library http.Server. It serves as a versatile routing mechanism that can handle middleware and nested routers efficiently.

Behavior:

  • The ServeMux stores the routing path to register middlewares and handlers.
  • If a pattern using the host conflicts with one that is already registered, it will cause a panic.

func NewServeMux

func NewServeMux(opts ...OptionServeMux) ServeMux

NewServeMux creates and returns a new instance of ServeMux with enhanced routing and middleware capabilities. A variadic set of OptionServeMux used to configure the behavior of the ServeMux.

Example
package main

import (
	"fmt"
	"log/slog"
	"net/http"
	"time"

	"github.com/telmoandrade/go-library/httpserver"
	"github.com/telmoandrade/go-library/logger"
	"go.opentelemetry.io/contrib/bridges/otelslog"
)

func handlerHello(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("hello"))
}

func main() {
	slog.SetDefault(logger.NewLogger(
		logger.WithMinLevel(slog.LevelInfo),
		logger.WithHandler(otelslog.NewHandler("")),
	))

	mux := httpserver.NewServeMux()

	mux.Use(
		httpserver.MiddlewareLogging,
		httpserver.MiddlewareRecover,
		httpserver.MiddlewareTrace,
	)

	mux.Get("/hello", handlerHello)

	s := &http.Server{
		Addr:              "0.0.0.0:8080",
		Handler:           mux,
		ReadHeaderTimeout: 15 * time.Second,
		ReadTimeout:       15 * time.Second,
		WriteTimeout:      10 * time.Second,
		IdleTimeout:       30 * time.Second,
	}
	fmt.Print(s != nil)
}
Output:

true

Jump to

Keyboard shortcuts

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