output

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2024 License: MIT Imports: 7 Imported by: 32

README

Introduction:

This package provides functions for returning data to HTTP API calls in a consistent manner so clients can comprehend the data more easily.

Details:

  • Returns data as JSON.
  • Each object returned has a status, a message type, the arbitrary data being returned, and a timestamp.
  • Can be used for successful and error states.
  • Message types allow for clients to understand various data coming from one endpoint.

Data Format:

  • OK: boolean.
  • Type: string.
  • Data: interface, can be anything. Structs are encoded as JS objects.
  • Datetime: YYYY-MM-DD HH:MM:SS.sss string in UTC timezone.
  • ErrorData: object with Error and Message fields.

Message Types:

There are predefined message types included in the package that are used with the defined helper funcs (InsertOK, DataFound, Error, etc.). However, you can define your own message types and use them with Success.

It is strongly advised to limit your custom message types, and keep track of them well, to reduce the inclination to "just use a new message type" with each response. This is more important in larger projects where different authors may create their own, sometimes overlapping, message types.

Use:

This package was designed to send back data from a webapp to client-side JS code that interacts and renders the GUI. Having a consistent format was also nice for logging and diagnostics.

In most cases, you will use the higher level functions (InsertOK, UpdateOK, etc.) instead of Success as these functions will set a message type automatically and reduce the amount of code typed in your projects.

Some demo code:

//success
mt := output.MessageType("myCustomMessagType")
data := map[string]string{
    "key": "value",
    "wyle": "e coyote",
}
output.Success(mt, data, w)

//error
err := funcThatCausesError()
output.Error(err, "Human readable error message or how to fix the error.", w)

Documentation

Overview

Package output is used to return data from requests to an HTTP API and present the returned data in a consistent manner for ease of comprehension by clients.

The returned data has a strict format except for user-defined data stored in the returned data's Data field. The returned data has a message type, a status, the arbitrary user-defined data, and a timestamp.

The message type field, Type, is used by clients to understand the topic of the returned data. Typically you would choose a message type from a predefined list (either defined in this package or defined by you prior to use) to reduce the possible message types a client would need to expect. Message types are short, descriptive titles to the returned data.

The status field, OK, is a boolean field that simply states if an error occured while processing the request.

The arbitrary data being returned is stored in one of two fields, depending on if an error occured (and OK is false). We use two fields, instead of one, so that we can store error data a bit differently (storing machine-readable error type and human-readable error message), and so that clients don't check that OK is false and assume a mistake since the Data field will be empty.

The main functions you will use are Success and Error, with the helper functions InsertOK, UpdateOK, DataFound, being used in place of Success. The error returned from these functions can usually be ignored; the error is only useful if you are defining custom message types, EnforceStrictMessageTypes is enabled, and you used a not-previously defined message type in the call to Success or its wrapper functions. The error will report that you must use a defined message type.

Index

Constants

This section is empty.

Variables

View Source
var (
	//ErrInvalidResponseCode is returned when a non-existant HTTP status code is
	//provided.
	ErrInvalidResponseCode = errors.New("output: invalid HTTP response code")
)

Define errors that can occur with our funcs that prevent writing responses and that the parent func calling of the of funcs in this package needs to handle.

Functions

func DataFound

func DataFound(data interface{}, w http.ResponseWriter) (err error)

DataFound is used to send back data in a response. This is typically used with looking up data from a database.

func Debug

func Debug(b bool)

Debug turns debug logging on or off.

func Error

func Error(errType error, errMsg string, w http.ResponseWriter) (err error)

Error is used when an error occured with a request and one of the other error response funcs (ErrorInputInvalid, etc.) doesn't fit.

Error, and related functions, always returns an HTTP status 500.

func ErrorAlreadyExists

func ErrorAlreadyExists(msg string, w http.ResponseWriter) (err error)

ErrorAlreadyExists is used when trying to insert something into the db that already exists.

func ErrorInputInvalid

func ErrorInputInvalid(msg string, w http.ResponseWriter) (err error)

ErrorInputInvalid is used when an error occurs while performing input validation.

func ErrorInputInvalidWithID

func ErrorInputInvalidWithID(msg string, id int64, w http.ResponseWriter) (err error)

ErrorInputInvalidWithID is similar to ErrorInputInvalid but allows for returning an I when an input validation error occured. This is used when you saved some data to a database and you want subsequent requests to "retry" using the existing ID instead of recreating records over an over with each error.

func ErrorWithID

func ErrorWithID(errType error, errMsg string, id int64, w http.ResponseWriter) (err error)

ErrorWithID is similar to Error but allows for returning an ID and the error data. This is used when you saved some data to a database and you want subsequent request to "retry" using the existing ID instead of recreating records over an over with each error.

func InsertOK

func InsertOK(id int64, w http.ResponseWriter) (err error)

InsertOK is used when a request resulted in data being successfully inserted into a database. This allows for sending by the just inserted data's ID.

func InsertOKWithData

func InsertOKWithData(data interface{}, w http.ResponseWriter) (err error)

InsertOKWithData is used when a request resulted in data being successfully inserted into a database and you want to send back a bunch of data with the response. While InsertOK can only send back an integer ID, this can send back anything.

func Send added in v1.1.0

func Send(p Payload, w http.ResponseWriter, responseCode int) (err error)

Send is used to send any response, with any payload, and any response code. This is meant to be used in situations where the Success and Error (and related helper funcs) do not provide enough control over the response, specifically when you want to use non-200 and -500 HTTP status codes.

func Success

func Success(msgType string, data interface{}, w http.ResponseWriter) (err error)

Success is used when a request was successful and one of the other successful response funcs (InsertOK, UpdateOK, DataFound, etc.) doesn't fit. While an error is returned, it is typically ignored.

Success, and related functions, always returns an HTTP status 200.

func UpdateOK

func UpdateOK(w http.ResponseWriter) (err error)

UpdateOK is used when a request resulted in data being successfully updated in a database.

func UpdateOKWithData

func UpdateOKWithData(data interface{}, w http.ResponseWriter) (err error)

UpdateOKWithData is used when a request resulted in data being successfully updated in a database and you want to send back a bunch of data with the response.

Types

type ErrorPayload

type ErrorPayload struct {
	//Error is a lower-level error, typically an err returned from a func.
	Error string `json:",omitempty"`

	//Message is a higher-level, more human-friendly, message that can be displayed
	//in a GUI and explains how to resolve the error.
	Message string `json:",omitempty"`
}

ErrorPayload is descriptive data about an error.

type Payload

type Payload struct {
	//OK reports the overall status of a request.
	//
	//If OK is true, the request was completed successfully.
	//If OK is false, an error occured during handling of the request.
	OK bool

	//Type is a descriptive title for response data so that clients can understand
	//the data in the response. You would typically use one of the defined message
	//types, or one of the functions that sets a message type automatically, although
	//you can define your own custom message types as needed.
	Type string

	//Data is arbitrary data to send back to the client. This is the data from you
	//application.
	//
	//This field is typically only populated when OK is true, however, it can be
	//populated in rare circumstances when OK is false (see ErrorWithID).
	Data interface{} `json:",omitempty"`

	//ErrorData is the data returned when an error occurs. We use a different field
	//when returning error data to reduce confusion. A lower-level error type and a
	//human-readable error message are returned.
	//
	//This field is only populated when OK is false.
	ErrorData ErrorPayload `json:",omitempty"`

	//Datetime is simply a timestamp of when a mesage was created. This is typically
	//used for diagnostics on the client side. It is YYYY-MM-DD HH:MM:SS.sss
	//formatted in the UTC timezone.
	Datetime string
}

Payload is the format of the data that will be sent back to the requestor client. This format is designed so that data being returned to the client is always in a consistent format.

Jump to

Keyboard shortcuts

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