util

package module
v0.2.5 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2025 License: Apache-2.0 Imports: 18 Imported by: 78

README

util

GoDoc Coverage Status

A loose collection of Golang functions to simplify reusability

Documentation

Index

Constants

View Source
const (
	StatusFound               = 302
	StatusInternalServerError = 500
	DefaultRequestIDLength    = 12
	Status2xx                 = 2
)
View Source
const (
	CallerDepth  = 3
	FileLineAttr = 4
)

Variables

This section is empty.

Functions

func ContextWithLogger

func ContextWithLogger(ctx context.Context, logger *LogEntry) context.Context

ContextWithLogger pushes a LogEntry instance into the supplied context for easier propagation.

func ContextWithRequestID added in v0.2.4

func ContextWithRequestID(ctx context.Context, requestID string) context.Context

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID returns the request ID associated with this context, or the empty string if one is not associated with this context.

func IDString added in v0.1.3

func IDString() string

func IDStringWithTime added in v0.1.3

func IDStringWithTime(t time.Time) string

func MakeJSONAPI

func MakeJSONAPI(handler JSONRequestHandler) http.HandlerFunc

MakeJSONAPI creates an HTTP handler which always responds to incoming requests with JSON responses. Incoming http.Requests will have a logger (with a request ID/method/path logged) attached to the Context. This can be accessed via GetLogger(Context).

func ParseLevel added in v0.2.0

func ParseLevel(levelStr string) (slog.Level, error)

ParseLevel converts a string to a log.Level. It is case-insensitive. Returns an error if the string does not match a known level.

func Protect

func Protect(handler http.HandlerFunc) http.HandlerFunc

Protect panicking HTTP requests from taking down the entire process, and log them using the correct logger, returning a 500 with a JSON response rather than abruptly closing the connection. The http.Request MUST have a ctxValueLogger.

func RandomString

func RandomString(n int) string

RandomString generates a cryptographically secure random string of length n.

func RequestWithLogging

func RequestWithLogging(req *http.Request) *http.Request

RequestWithLogging sets up standard logging for http.Requests. http.Requests will have a logger (with a request ID/method/path logged) attached to the Context. This can be accessed via GetLogger(Context).

func SLog added in v0.2.0

func SLog(ctx context.Context) *slog.Logger

SLog obtains an slog interface from the log entry in the context.

func SetCORSHeaders

func SetCORSHeaders(w http.ResponseWriter)

SetCORSHeaders sets unrestricted origin Access-Control headers on the response writer.

func SortAndUnique

func SortAndUnique(data sort.Interface) int

SortAndUnique sorts the data and removes duplicates. O(nlog(n)).

func Unique

func Unique(data sort.Interface) int

Unique removes duplicate items from a sorted list in place. Takes the same interface as sort.Sort Returns the length of the data without duplicates Uses the last occurrence of a duplicate. O(n).

func UniqueStrings

func UniqueStrings(strings []string) []string

UniqueStrings returns a sorted slice of unique strings. O(nlog(n)).

func WithCORSOptions

func WithCORSOptions(handler http.HandlerFunc) http.HandlerFunc

WithCORSOptions intercepts all OPTIONS requests and responds with CORS headers. The request handler is not invoked when this happens.

Types

type JSONRequestHandler

type JSONRequestHandler interface {
	OnIncomingRequest(req *http.Request) JSONResponse
}

JSONRequestHandler represents an interface that must be satisfied in order to respond to incoming HTTP requests with JSON.

func NewJSONRequestHandler

func NewJSONRequestHandler(f func(req *http.Request) JSONResponse) JSONRequestHandler

NewJSONRequestHandler converts the given OnIncomingRequest function into a JSONRequestHandler.

type JSONResponse

type JSONResponse struct {
	// HTTP status code.
	Code int
	// JSON represents the JSON that should be serialised and sent to the client
	JSON interface{}
	// Headers represent any headers that should be sent to the client
	Headers map[string]any
}

JSONResponse represents an HTTP response which contains a JSON body.

func ErrorResponse

func ErrorResponse(err error) JSONResponse

ErrorResponse returns an HTTP 500 JSONResponse with the stringified form of the given error.

func MatrixErrorResponse

func MatrixErrorResponse(httpStatusCode int, errCode, message string) JSONResponse

MatrixErrorResponse is a function that returns error responses in the standard Matrix Error format (errcode / error).

func MessageResponse

func MessageResponse(code int, msg string) JSONResponse

MessageResponse returns a JSONResponse with a 'message' key containing the given text.

func RedirectResponse

func RedirectResponse(location string) JSONResponse

RedirectResponse returns a JSONResponse which 302s the client to the given location.

func (JSONResponse) Is2xx

func (r JSONResponse) Is2xx() bool

Is2xx returns true if the Code is between 200 and 299.

type LogEntry added in v0.2.0

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

LogEntry handles logging functionality with immutable chained calls.

func Log added in v0.2.0

func Log(ctx context.Context) *LogEntry

Log obtains a service instance being propagated through the context.

func NewLogger added in v0.2.1

func NewLogger(ctx context.Context, opts *LogOptions) *LogEntry

NewLogger creates a new instance of LogEntry with the provided context and options.

func (*LogEntry) Debug added in v0.2.0

func (e *LogEntry) Debug(msg string, args ...any)

Debug logs a message at debug level.

func (*LogEntry) Enabled added in v0.2.5

func (e *LogEntry) Enabled(ctx context.Context, level slog.Level) bool

Enabled returns whether the logger will log at the given level.

func (*LogEntry) Error added in v0.2.0

func (e *LogEntry) Error(msg string, args ...any)

Error logs a message at error level.

func (*LogEntry) Exit added in v0.2.5

func (e *LogEntry) Exit(code int)

Exit terminates the application with the given code.

func (*LogEntry) Fatal added in v0.2.0

func (e *LogEntry) Fatal(msg string, args ...any)

Fatal logs a message at error level and exits with code 1.

func (*LogEntry) Info added in v0.2.0

func (e *LogEntry) Info(msg string, args ...any)

Info logs a message at info level.

func (*LogEntry) LevelEnabled added in v0.2.0

func (e *LogEntry) LevelEnabled(ctx context.Context, level slog.Level) bool

LevelEnabled is an alias for Enabled for backward compatibility.

func (*LogEntry) Log added in v0.2.0

func (e *LogEntry) Log(ctx context.Context, level slog.Level, msg string, fields ...any)

Log logs a message at the given level.

func (*LogEntry) Logf added in v0.2.3

func (e *LogEntry) Logf(ctx context.Context, level slog.Level, format string, args ...interface{})

Logf logs a formatted message at the given level.

func (*LogEntry) Panic added in v0.2.0

func (e *LogEntry) Panic(msg string, _ ...any)

Panic logs a message and panics.

func (*LogEntry) Printf added in v0.2.0

func (e *LogEntry) Printf(format string, args ...any)

Printf logs a formatted message at info level.

func (*LogEntry) Release added in v0.2.5

func (e *LogEntry) Release()

Release returns the LogEntry to the pool for reuse. Call this when you're done with a LogEntry and won't use it again.

func (*LogEntry) SLog added in v0.2.2

func (e *LogEntry) SLog() *slog.Logger

SLog returns the underlying slog.Logger.

func (*LogEntry) Trace added in v0.2.0

func (e *LogEntry) Trace(msg string, args ...any)

Trace logs a message at debug level (alias for backward compatibility).

func (*LogEntry) Warn added in v0.2.0

func (e *LogEntry) Warn(msg string, args ...any)

Warn logs a message at warn level.

func (*LogEntry) With added in v0.2.0

func (e *LogEntry) With(args ...any) *LogEntry

With returns a new LogEntry with the provided attributes added.

func (*LogEntry) WithContext added in v0.2.0

func (e *LogEntry) WithContext(ctx context.Context) *LogEntry

WithContext returns a new LogEntry with the given context.

func (*LogEntry) WithError added in v0.2.0

func (e *LogEntry) WithError(err error) *LogEntry

WithError returns a new LogEntry with the error added.

func (*LogEntry) WithField added in v0.2.0

func (e *LogEntry) WithField(key string, value any) *LogEntry

WithField returns a new LogEntry with the field added.

type LogOptions added in v0.2.1

type LogOptions struct {
	*slog.HandlerOptions
	PrintFormat    string
	TimeFormat     string
	NoColor        bool
	ShowStackTrace bool
}

func DefaultLogOptions added in v0.2.1

func DefaultLogOptions() *LogOptions

Jump to

Keyboard shortcuts

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