package webutils

import "git.mstar.dev/mstar/goutils/http"

Package webutils contains various functions for easier interaction and common tasks when working with net/http.Handler based webservers

Index

Variables

var (
	ErrWriterNotFlushable = errors.New("response writer not flushable")
)

Functions

func ChainMiddlewares

func ChainMiddlewares(base http.Handler, links ...HandlerBuilder) http.Handler

func HttpErr

func HttpErr(w http.ResponseWriter, errId int, message string, code int) error

Return an error over an http connection. The error will have the given return code `code` and a json encoded body with the field "id" set to `errId` and a field "message" set to the `message`

Deprecated: Use ProblemDetails or ProblemDetailsStatusOnly instead

func LoggingMiddleware

func LoggingMiddleware(handler http.Handler) http.Handler

func ProblemDetails

func ProblemDetails(
	w http.ResponseWriter,
	statusCode int,
	errorType string,
	errorTitle string,
	details *string,
	extras map[string]any,
) error

Write an RFC 9457 compliant problem details response If details is not nil, it will be included. If extras is not nil, each key-value pair will be included at the root layer. Keys in extras that would overwrite the default elements will be ignored. Those would be "type", "status", "title" and "detail"

func ProblemDetailsStatusOnly

func ProblemDetailsStatusOnly(w http.ResponseWriter, statusCode int) error

Write a simple problem details response. It only provides the status code, as defined in RFC 9457, section 4.2.1

func RealIpAppenderMiddleware

func RealIpAppenderMiddleware(fieldKey string) func(handler http.Handler) http.Handler

hlog.RemoteAddrHandler except fixed to check the X-Real-Ip and X-Forwarded-For headers first for the IP instead of relying on RemoteAddr (which would only return the last proxy's address instead of the caller's)

func SendJson

func SendJson(w http.ResponseWriter, data any) error

func SseWriter

func SseWriter(w http.ResponseWriter, dataStream chan []byte) error

SseWriter provides a simple implementation for sending data via Server Side Events to the client. The function runs until the dataStream channel is closed. The ResponseWriter must not be used after calling this function

Inspired by and partially copied from https://medium.com/@rian.eka.cahya/server-sent-event-sse-with-go-10592d9c2aa1

Types

type HandlerBuilder

type HandlerBuilder func(http.Handler) http.Handler

func BuildLoggingMiddleware

func BuildLoggingMiddleware(
	status500IsError bool,
	ignorePaths []string,
	extras map[string]string,
) HandlerBuilder

func ContextValsMiddleware

func ContextValsMiddleware(pairs map[any]any) HandlerBuilder

Source Files

chain.go context.go httpErr.go json.go sse.go zerolog.go

Version
v1.15.0 (latest)
Published
Jun 6, 2025
Platform
linux/amd64
Imports
12 packages
Last checked
1 hour ago

Tools for package owners.