apio

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 1, 2022 License: MIT Imports: 11 Imported by: 12

Documentation

Overview

Package apio contains helpers for consistent input parsing and output response from our API.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DecodeJSONBody

func DecodeJSONBody(w http.ResponseWriter, r *http.Request, dst interface{}) error

DecodeJSONBody decodes a JSON body and returns client-friendly errors.

func Error

func Error(ctx context.Context, w http.ResponseWriter, err error)

Error sends an error reponse back to the client and logs the error internally. If the error is of type apio.Error we will send the error message back to the client. Otherwise, we return a HTTP 500 code with an opaque response to avoid leaking any information from the server.

Under the hood, Error uses logger.Get() to load a zap logger from the provided context.

The response body is in the format:

{"error": "msg"}

If errhandler.Handler is set in the context, it will always be called with the error. You can check the error type in your error handler to determine the status code of the error.

func ErrorString added in v0.2.0

func ErrorString(ctx context.Context, w http.ResponseWriter, msg string, code int)

ErrorString sends an error response designated status code and error message. The response body is in the format:

{"error": "msg"}

It's a convenience wrapper over apio.Error().

func JSON

func JSON(ctx context.Context, w http.ResponseWriter, data interface{}, statusCode int)

JSON converts a Go value to JSON and sends it to the client. Under the hood, JSON uses logger.Get() to load a zap logger from the provided context.

func NewRequestError

func NewRequestError(err error, status int) error

NewRequestError wraps a provided error with an HTTP status code. This function should be used when handlers encounter expected errors.

Types

type APIError

type APIError struct {
	Err    error
	Status int
	Fields []FieldError
}

APIError is used to pass an error during the request through the application with web specific context.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface. It uses the default message of the wrapped error. This is what will be shown in the services' logs.

type ErrorResponse

type ErrorResponse struct {
	Error  string       `json:"error"`
	Fields []FieldError `json:"fields,omitempty"`
}

ErrorResponse is the form used for API responses from failures in the API.

type FieldError

type FieldError struct {
	Field string `json:"field"`
	Error string `json:"error"`
}

FieldError is used to indicate an error with a specific request field.

Jump to

Keyboard shortcuts

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