goforge

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 27, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package goforge defines the shared contracts and primitives used throughout the GoForge modules.

It keeps service-facing concerns such as structured errors, JSON responses, context-scoped logging, and endpoint registration consistent without imposing an application framework. Specialized integrations live in independently versioned modules.

A typical service uses chassis as its inbound HTTP foundation. chassis.NewServeMux starts with the standard library's routing behavior and adds only the logging, recovery, tracing, authentication, CORS, caching, or application middleware the service selects. The httpmiddlewares module exposes those building blocks directly when a service does not need the chassis abstraction.

For outbound HTTP, httpclient.NewClient builds a standard http.Client whose transport can be composed with authentication and OpenTelemetry instrumentation. httpclient.Call can then form the typed JSON execution layer beneath small service-specific SDKs.

The storage, messaging, error-reporting, and tooling modules complement these inbound and outbound foundations. Each module is independently versioned, so applications can adopt only the integrations they need while sharing the contracts defined by this root package.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func FormatStackTrace

func FormatStackTrace(stack []StackFrame) string

FormatStackTrace formats captured stack frames into a multi-line string.

func LoggerFromContext

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

LoggerFromContext retrieves the logger from the context. If no logger is found, it returns a default logger.

func LoggerFromContextOr added in v0.2.0

func LoggerFromContextOr(ctx context.Context, fallback *slog.Logger) *slog.Logger

LoggerFromContextOr retrieves the logger from the context, falling back to fallback when no logger is present. A nil fallback uses the default logger.

func PtrValue

func PtrValue[T any](p *T) T

func RespondError

func RespondError(w http.ResponseWriter, err error) error

func RespondJSON

func RespondJSON[T any](w http.ResponseWriter, data T, statusCode int) error
Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"

	"github.com/lgosse/goforge"
)

func main() {
	recorder := httptest.NewRecorder()

	err := goforge.RespondJSON(recorder, struct {
		ID string `json:"id"`
	}{ID: "user-1"}, http.StatusCreated)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(recorder.Code)
	fmt.Println(recorder.Header().Get("Content-Type"))
	fmt.Println(recorder.Body.String())
}
Output:
201
application/json
{"id":"user-1"}

func WithLogger

func WithLogger(ctx context.Context, logger *slog.Logger) context.Context

WithLogger adds a *log/slog.Logger to the context.

Types

type Endpoint

type Endpoint interface {
	Scheme() string
	Host() string
	Method() string
	Path() string
	Headers() http.Header
}

Endpoint is the standard contract for all goforge endpoints.

type EndpointRegistry

type EndpointRegistry interface {
	Register(endpoint Endpoint) error
	Start() error
}

EndpointRegistry is the standard contract for goforge endpoint registry.

type Error

type Error struct {
	HTTPStatus int          // E.g., 400, 404, 500
	Code       string       // Internal tracking code, e.g., "ERR_USER_FORBIDDEN_PASSWORD_CHANGE", can be used for user-facing translations.
	Message    string       // Safe, user-facing message
	Cause      error        // The underlying wrapped error for logs (should not be exposed to clients)
	Stack      []StackFrame // Captured call stack for logs and error reporters such as Sentry.
}

Error is the standard contract for all goforge errors.

func NewError

func NewError(cause error) *Error

NewError creates a new goforge error with a default 500 status code and the given cause.

Example
package main

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/lgosse/goforge"
)

func main() {
	err := goforge.NewError(errors.New("user does not exist")).
		WithHTTPStatus(http.StatusNotFound).
		WithCode("ERR_USER_NOT_FOUND").
		WithMessage("User not found")

	fmt.Println(err.HTTPStatus, err.Code, err.Message)
}
Output:
404 ERR_USER_NOT_FOUND User not found

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) StackTrace

func (e *Error) StackTrace() []StackFrame

StackTrace returns a defensive copy of the captured stack frames.

func (*Error) StackTraceString

func (e *Error) StackTraceString() string

StackTraceString formats the captured stack in the same file:line/function shape most log sinks and error reporters expect.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap allows standard errors.Is and errors.As to work perfectly.

func (*Error) WithCapturedStack

func (e *Error) WithCapturedStack(skip int) *Error

WithCapturedStack captures a fresh stack trace. The skip value excludes additional caller frames above WithCapturedStack.

func (*Error) WithCode

func (e *Error) WithCode(code string) *Error

WithCode sets the internal tracking code for the error.

func (*Error) WithHTTPStatus

func (e *Error) WithHTTPStatus(status int) *Error

WithHTTPStatus sets the HTTP status code for the error.

func (*Error) WithMessage

func (e *Error) WithMessage(message string) *Error

WithMessage sets the user-facing message for the error.

func (*Error) WithStack

func (e *Error) WithStack(stack []StackFrame) *Error

WithStack replaces the captured stack frames.

type StackFrame

type StackFrame struct {
	Function       string
	File           string
	Line           int
	ProgramCounter uintptr
}

StackFrame is a single call frame captured when a goforge error is created.

func CaptureStackTrace

func CaptureStackTrace(skip int) []StackFrame

CaptureStackTrace captures the current goroutine stack. The skip value excludes additional caller frames above CaptureStackTrace.

Directories

Path Synopsis
chassis module
forgemongo module
forgesentry module
httpclient module
otel module
mongo module

Jump to

Keyboard shortcuts

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