rest

package module
v0.0.0-...-727a744 Latest Latest
Warning

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

Go to latest
Published: Jul 19, 2024 License: MIT Imports: 4 Imported by: 0

README

Go REST

Some handy functions for developing JSON-based REST APIs. In particular, it simplifies reading HTTP request bodies, writing HTTP response bodies, and handling errors.

Error handling

You can use errors.Is() to ascertain the type of errors thrown by validation functions, but for the most part, this isn't necessary because the write functions already do that.

Example

package main

import (
	"errors"
	"math/rand"
	"net/http"

	"github.com/annybs/go/rest"
)

type Handler struct{}

func (*Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	n := rand.Intn(3)
	if n == 0 {
		rest.WriteResponseJSON(w, http.StatusOK, map[string]string{"status": "OK"})
	} else if n == 1 {
		rest.WriteErrorJSON(w, errors.New("the original error message is added to data.error"))
	} else {
		rest.WriteErrorJSON(w, rest.ErrNotFound)
	}
}

func main() {
	http.ListenAndServe("localhost:8000", &Handler{})
}

Open http://localhost:8000 in your browser and refresh a bunch of times to see the different possible responses.

License

See LICENSE.md

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Err = Error{}

	ErrMovedPermanently  = NewError(http.StatusMovedPermanently, "")  // 301
	ErrFound             = NewError(http.StatusFound, "")             // 302
	ErrTemporaryRedirect = NewError(http.StatusTemporaryRedirect, "") // 307
	ErrPermanentRedirect = NewError(http.StatusPermanentRedirect, "") // 308

	ErrBadRequest       = NewError(http.StatusBadRequest, "")       // 400
	ErrUnauthorized     = NewError(http.StatusUnauthorized, "")     // 401
	ErrPaymentRequired  = NewError(http.StatusPaymentRequired, "")  // 402
	ErrForbidden        = NewError(http.StatusForbidden, "")        // 403
	ErrNotFound         = NewError(http.StatusNotFound, "")         // 404
	ErrMethodNotAllowed = NewError(http.StatusMethodNotAllowed, "") // 405
	ErrNotAcceptable    = NewError(http.StatusNotAcceptable, "")    // 406

	ErrInternalServerError = NewError(http.StatusInternalServerError, "") // 500
	ErrNotImplemented      = NewError(http.StatusNotImplemented, "")      // 501
	ErrBadGateway          = NewError(http.StatusBadGateway, "")          // 502
	ErrServiceUnavailable  = NewError(http.StatusServiceUnavailable, "")  // 503
	ErrGatewayTimeout      = NewError(http.StatusGatewayTimeout, "")      // 504
)

REST API error.

Functions

func IsAuthenticated

func IsAuthenticated(req *http.Request, token string) bool

IsAuthenticated returns true if the bearer token in a request's authorization is equal to a user-defined token. This function always returns true if the user-defined token is empty i.e. no authentication required.

func ReadBearerToken

func ReadBearerToken(req *http.Request) string

ReadBearerToken reads the token portion of a bearer token in a request's authorization header. This function returns an empty string if the header is not provided or is not a bearer token.

func ReadRequestJSON

func ReadRequestJSON(req *http.Request, v any) error

ReadRequestJSON reads the body of an HTTP request into a target reference.

func WriteError

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

WriteError writes an error to an HTTP response. If the error is a REST API error, it is written as standard per Error.Write. Otherwise, ErrInternalServerError is written with the given error attached as data.

func WriteErrorJSON

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

WriteErrorJSON writes an error as JSON to an HTTP response. If the error is a REST API error, it is written as standard per Error.WriteJSON. Otherwise, ErrInternalServerError is written with the given error attached as data.

func WriteResponseJSON

func WriteResponseJSON(w http.ResponseWriter, statusCode int, data any) error

WriteResponseJSON writes an HTTP response as JSON.

Types

type Error

type Error struct {
	StatusCode int                    `json:"-"`              // HTTP status code (200, 404, 500 etc.)
	Message    string                 `json:"message"`        // Status message ("OK", "Not found", "Internal server error" etc.)
	Data       map[string]interface{} `json:"data,omitempty"` // Optional additional data.
}

Error represents a REST API error. It can be marshaled to JSON with ease and provides a standard format for printing errors and additional data.

func NewError

func NewError(statusCode int, message string) Error

NewError creates a new REST API error. If the message is empty, the standard text provided by http.StatusText is substituted.

func (Error) Error

func (e Error) Error() string

Error retrieves the message of a REST API error.

func (Error) Is

func (e Error) Is(target error) bool

Is determines whether the Error is an instance of the target. https://pkg.go.dev/errors#Is

If the target is a REST API error and specifies a status code, this function returns true if the status codes match. If the target is an empty REST API error, this function always returns true.

func (Error) WithData

func (e Error) WithData(data map[string]interface{}) Error

WithData returns a copy of the HTTP error with the given data merged in.

func (Error) WithError

func (e Error) WithError(err error) Error

WithError returns a copy of the HTTP error with the given error added either as the Message, if it empty, or as additional data.

func (Error) WithMessage

func (e Error) WithMessage(message string) Error

WithMessage returns a copy of the HTTP error with the given message.

func (Error) WithValue

func (e Error) WithValue(name string, value any) Error

WithValue returns a copy of the HTTP error with a single data value added.

func (Error) Write

func (e Error) Write(w http.ResponseWriter) (int, error)

Write writes the HTTP error to an HTTP response as plain text. Additional data is omitted.

func (Error) WriteJSON

func (e Error) WriteJSON(w http.ResponseWriter) error

WriteJSON writes the HTTP error to an HTTP response as JSON.

Jump to

Keyboard shortcuts

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