Documentation
¶
Overview ¶
Package util provides REST utilties used by 'cbbs'.
Index ¶
- Constants
- Variables
- func AuthMiddlewareHandler(noAuth bool, permission, userFriendlyName string, w http.ResponseWriter, ...) error
- func DecodeJSONRequestBody(body io.ReadCloser, dest any, w http.ResponseWriter) bool
- func HandleErrorWithExtras(errRes ErrorResponse, w http.ResponseWriter, errLog ErrLogFn)
- func MarshalAndSend(status int, data any, w http.ResponseWriter, errLog ErrLogFn)
- func SendJSONResponse(status int, data []byte, w http.ResponseWriter, errLog ErrLogFn)
- type ErrLogFn
- type ErrorResponse
Constants ¶
const MaxRequestBodySize = 10 * 1024 * 1024
MaxRequestBodySize is a maximum of data that will be read from a request body in bytes.
Variables ¶
var ( ErrForbidden = errors.New("forbidden") ErrCouldNotAuthenticate = errors.New("could not authenticate user") )
Functions ¶
func AuthMiddlewareHandler ¶ added in v1.1.0
func DecodeJSONRequestBody ¶
func DecodeJSONRequestBody(body io.ReadCloser, dest any, w http.ResponseWriter) bool
DecodeJSONRequestBody tries to decode the body as JSON. If it fails it will send a 400 response and return false. Otherwise it will return true and decode the body into dest.
func HandleErrorWithExtras ¶
func HandleErrorWithExtras(errRes ErrorResponse, w http.ResponseWriter, errLog ErrLogFn)
HandleErrorWithExtras marshals and sends the ErrorResponse as JSON. If an error log function is provided it will be called if there are issues marshaling or writing the data to the response writer.
func MarshalAndSend ¶
func MarshalAndSend(status int, data any, w http.ResponseWriter, errLog ErrLogFn)
MarshalAndSend will try and marshal the given interface, if it fails it will write an ErrorResponse to the client with status 500 and a message saying that the response could not be marshaled. Otherwise it will send the marshaled content.
func SendJSONResponse ¶
func SendJSONResponse(status int, data []byte, w http.ResponseWriter, errLog ErrLogFn)
SendJSONResponse sends a response with the given status code with the body "data" and content type application/json. If the error log function is given it will be used if it encounters an error while writing the response.
Types ¶
type ErrLogFn ¶
type ErrLogFn func(err error)
ErrLogFn is a callback function used to log errors occurred in the functions of this package.
type ErrorResponse ¶
type ErrorResponse struct {
Status int `json:"status"`
Msg string `json:"msg"`
Extras string `json:"extras,omitempty"`
}
ErrorResponse is a struct that defines a basic structure for REST errors. Status should be the HTTPCode for the response. The Msg should be a user friendly error that explains what occurs. Extras can be left empty. If included it should contain more in depth details about the error.