httpruntime

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2026 License: MIT Imports: 4 Imported by: 0

Documentation

Overview

Package httpruntime provides runtime helpers for generated HTTP handler functions. It defines the unified response envelope (Response), error types (Error, CodedError), and DefaultErrorHandler middleware for gin-based services.

Package httpruntime provides runtime helpers for generated HTTP handler functions. It defines the response envelope, error type, and CodedError interface used by generated .pb.http.go files.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultErrorHandler

func DefaultErrorHandler() gin.HandlerFunc

DefaultErrorHandler returns a gin middleware that writes a JSON error response for any errors accumulated via c.Error() during handler execution. ValidationError maps to code 400; all other errors map to code 500 (or the code returned by CodedError.Code() if the error implements that interface). Only the last error (c.Errors.Last()) is used when multiple errors are present.

WARNING: Generated handlers use c.Error(err)+return and do not write their own error responses. If this middleware is not registered, error paths will return HTTP 200 with an empty body. Always register DefaultErrorHandler (or a custom equivalent) on any router that serves generated handlers.

Types

type CodedError

type CodedError interface {
	Code() int
}

CodedError may be implemented by application errors to supply a custom business error code (not an HTTP status code). If an error passed to ErrResponse implements this interface, its Code() value is used; otherwise the default code 500 applies.

type Error

type Error struct {
	Msg    string         `json:"msg"`
	Fields map[string]any `json:"fields,omitempty"`
}

Error carries error details inside a Response. Fields is an optional map for structured error metadata (e.g. per-field validation failures).

type Response

type Response struct {
	Code  int    `json:"code"`
	Data  any    `json:"data,omitempty"`
	Error *Error `json:"error,omitempty"`
}

Response is the JSON envelope returned by all generated HTTP handlers. Code 0 indicates success; non-zero indicates an error.

func ErrResponse

func ErrResponse(err error) Response

ErrResponse constructs an error Response from err. If err implements CodedError, its Code() is used as the response code. Otherwise the response code defaults to 500. If err is nil, ErrResponse returns a generic code-500 error response.

func OKResponse

func OKResponse(data any) Response

OKResponse constructs a success Response with code 0 and the given data.

Jump to

Keyboard shortcuts

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