jsonx

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 18, 2025 License: MIT Imports: 6 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidJSON          = errors.New("invalid JSON format")
	ErrInvalidTarget        = errors.New("decode target must be a non-nil pointer")
	ErrNoContent            = errors.New("no content to decode")
	ErrUnsupportedMediaType = errors.New("unsupported media type, expected application/json")
)

Functions

func DecodeJSON

func DecodeJSON(r io.Reader, target any) error

DecodeJSON decodes JSON from an io.Reader into the provided target

func DecodeJSONFromRequest

func DecodeJSONFromRequest(r *http.Request, target any, opts ...Options) error

DecodeJSONFromRequest decodes JSON from an HTTP request body

func EncodeJSON

func EncodeJSON(w io.Writer, data any, opts ...Options) error

EncodeJSON encodes data to JSON and writes it to the provided writer

func RespondWithError

func RespondWithError(w http.ResponseWriter, err any, opts ...Options) error

RespondWithError writes a JSON error response

func RespondWithJSON

func RespondWithJSON(w http.ResponseWriter, data any, opts ...Options) error

RespondWithJSON writes a JSON response with appropriate headers

func RespondWithSuccess

func RespondWithSuccess(w http.ResponseWriter, data any, meta any, opts ...Options) error

RespondWithSuccess writes a standardized success response

func Send

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

Send is a shorthand for RespondWithJSON with default options

func SendError

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

SendError is a shorthand for RespondWithError with default options

func SendSuccess

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

SendSuccess is a shorthand for RespondWithSuccess with default options

Types

type ErrorDetail

type ErrorDetail struct {
	Code    string `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
}

ErrorDetail represents a structured error with code and message

type Options

type Options struct {
	SuccessStatus int
	ErrorStatus   int

	ContentType        string
	AllowEmpty         bool
	EnforceContentType bool
	Headers            map[string]string

	IndentResponse bool
	EscapeHTML     bool
}

func DefaultOptions

func DefaultOptions() Options

type Response

type Response struct {
	Success bool `json:"success"`
	Data    any  `json:"data"`
	Error   any  `json:"error"`
	Meta    any  `json:"meta"`
}

Jump to

Keyboard shortcuts

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