response

package module
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Apr 8, 2023 License: MIT Imports: 8 Imported by: 3

README

response

Response is simple helper for rest api responses. The naming of api functions is: for setter Value and for getter GetValue (Only exception is String so we satisfy Stringer interface). Let's see some examples:

response.New(http.StatusOK).Write(w, r)

// or with default OK status

response.New().Write(w, r)
    

This writes following response to ResponseWriter (w).

{
  "status": 200,
  "message": "OK"
}

Response adds ability to add various data to response object. You can use method Data to set data or there are some shorthand for usual data keys.


response.New().Data("result", result).Write(w, r)

// or with a shorthand

response.New().Result(result).Write(w, r)

There is also shorthand to provide slice result that automatiaclly adds result_size.

response.New().SliceResult(result).Write(w, r)
Shortcuts

response serves following shortcuts to create responses

  • Data
  • Error
  • HTML
  • Result
  • SliceResult
  • Write

Example:

result := map[string]string{}
response.Result(result)

Is the same as doing

result := map[string]string{}
response.New(http.StatusOK).Result(result)

or even

result := map[string]string{}
response.New().Result(result)
Contributions

You are welcome to send PR.

Documentation

Overview

Response helper interface for structured json responses. Response has also support to provide HTML content, but primarily it's

targeted to json rest apis

Response supports errors, raw content, etc..

Setter methods support chaining so writing response to http is doable on single line In next examples we use these variables

w http.ResponseWriter
r *http.Request

Example of responses

response.New(http.StatusInternalServerError).Error(errors.New("error")).Write(w, r)
response.New().Error(structError).Write(w, r)
response.New().Result(product).Write(w, r)
response.New().Result(products).ResultSize(size).Write(w, r)
response.New().SliceResult(products).Write(w, r)
response.New(http.StatusForbidden).Write(w, r)

Also there is non required argument status

body := map[string]string{
	"version": "1.0beta"
}
response.New(http.StatusOK).Body(body)Write(w, r)
response.New(http.StatusOK).Result(product).Write(w, r)
response.New(http.StatusOK).SliceResult(products).Write(w, r)

Minimal support for html responses

response.New().HTML("<html></html>").Write(w, r)

Index

Constants

View Source
const STATUS_HEADER = "X-Response-Status"

Variables

View Source
var (
	// CamelCaseFormat sets common keys as camel case
	CamelCaseFormat = KeyFormat{
		ErrorKey:      "Error",
		MessageKey:    "Message",
		ResultKey:     "Result",
		ResultSizeKey: "ResultSize",
		StatusKey:     "Status",
	}

	// SnakeCaseFormat sets common keys as snake case
	SnakeCaseFormat = KeyFormat{
		ErrorKey:      "error",
		MessageKey:    "message",
		ResultKey:     "result",
		ResultSizeKey: "result_size",
		StatusKey:     "status",
	}
)

Functions

func Format added in v0.3.0

func Format(f KeyFormat)

Format sets KeyFormat to given KeyFormat

func GetErrorStatus

func GetErrorStatus(err error) int

GetErrorStatus returns appropriate http status for given error

func RegisterError

func RegisterError(err error, status int)

RegisterError registers error to given http status

func Write

func Write(w http.ResponseWriter, r *http.Request)

Write writes to response and returns error

Types

type KeyFormat added in v0.3.3

type KeyFormat struct {
	ErrorKey      string
	MessageKey    string
	ResultKey     string
	ResultSizeKey string
	StatusKey     string
}

func CurrentFormat added in v0.3.3

func CurrentFormat() KeyFormat

CurrentFormat returns current key

type Response

type Response interface {

	// set raw body
	Body(body interface{}) Response

	// Set Content type
	ContentType(contenttype string) Response

	// set data to response data
	Data(key string, value interface{}) Response

	// delete data value identified by key
	DeleteData(key string) Response

	// delete header by name
	DeleteHeader(name string) Response

	// sets `error` to response data
	Error(err interface{}) Response

	// returns response as []byte
	GetBytes() []byte

	HasData(key string) bool
	// set header with value
	Header(name, value string) Response

	// set html and content type (for template rendering)
	HTML(html string) Response

	// set http message
	Message(message string) Response

	// custom json marshalling function
	MarshalJSON() (result []byte, err error)

	// set `result` on response data (shorthand for Data("result", data))
	Result(result interface{}) Response

	// set result_size on response
	ResultSize(size int) Response

	// set slice result (sets `result` and `result_size`)
	SliceResult(result interface{}) Response

	// set http status
	Status(status int) Response

	// return string value of response
	String() (body string)

	// Write complete response to writer
	Write(w http.ResponseWriter, request *http.Request)
}

Response interface provides several method for Response

func BadRequest

func BadRequest() Response

BadRequest returns response with StatusBadRequest

func Body

func Body(body interface{}) Response

Body is helper to create response

func Data

func Data(key string, value interface{}) Response

Data is helper to create status ok response.

func Error

func Error(err interface{}) Response

Error is helper to create status ok response.

func HTML

func HTML(html string) Response

HTML returns response set to HTML

func New

func New(statuses ...int) (result Response)

New returns new response instance, if no status is given StatusOK is used

func NotFound

func NotFound() Response

NotFound returns response with StatusNotFound

func OK

func OK() Response

OK returns response with StatusOK

func Result

func Result(result interface{}) Response

Result is helper to create status ok response.

func SliceResult

func SliceResult(result interface{}) Response

SliceResult is helper to create status ok response.

func Unauthorized

func Unauthorized() Response

Unauthorized returns response with StatusUnauthorized

Jump to

Keyboard shortcuts

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