respond

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2020 License: MIT Imports: 4 Imported by: 0

README

respond

Go

Package responds provides low touch, minimal API for sending HTTP API responses in go.

For simple string responses can be used simply as:

func handler(w http.ResponseWriter, r *http.Request) {
     respond.With(w, http.StatusOK, []byte(`Hello World!`))
}

For more complex use cases where we want to send JSON across this respond provides handy utility function which can be used as follows:

type response struct {
    Message string `json: "message"`
}

func handler(w http.ResponseWriter, r *http.Request) {
    resp := response{Message: "Hello World!"}
    respond.WithJSON(w, http.StatusOK, response)
}

While sending JSON responses correct HTTP Content-Type: applocation/json; utf-8 is also set.

Documentation

Overview

Package respond provides low touch API for sending HTTP responses.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func With

func With(w http.ResponseWriter, status int, data []byte) error

With sends the headers with the provided status then writes the data on the provided http.ResponseWriter.

If also overwrites the Content-Length header to the length of data byte slice provided.

If provided http.ResponseWriter errors while writing the response then a non-nil error is returned wrapping the original error.

func WithJSON

func WithJSON(w http.ResponseWriter, status int, data interface{}) error

WithJSON also sends the headers with the provided status then writes the data on the provided http.ResponseWriter after marshalling the data into json.

It also overwrites the the Content-Type header to application/json, if the provided data is non-nil.

If marshalling of the provided data fails or the http.ResponseWriter errors while writing the response then a non-nil error is returned wrapping the original error.

Types

This section is empty.

Jump to

Keyboard shortcuts

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