rest

package
v0.24.0 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2020 License: Apache-2.0 Imports: 6 Imported by: 1

README

REST

The response package provides ways to create HTTP + JSON responses in a consistent format. Below are usage example which demonstrate it's use.

Respond without data

package handlers

import (
	"net/http"
	
	"github.com/LUSHDigital/core/pagination"
	"github.com/LUSHDigital/core/rest"
)

func someHandler(w http.ResponseWriter, r *http.Request) {
    resp := &rest.Response{
        Code:    http.StatusOK,
        Message: "some helpful message",
    }
    resp.WriteTo(w)
}

Output

{
  "code": 200,
  "message": "some helpful message"
}

Respond with data

package handlers

import (
	"net/http"
	
	"github.com/LUSHDigital/core/pagination"
	"github.com/LUSHDigital/core/rest"
)

func someHandler(w http.ResponseWriter, r *http.Request) {
    someData := map[string]interface{}{
        "hello": "world",
    }
    
    resp := &rest.Response{
        Code:    http.StatusOK,
        Message: "some helpful message",
        Data: &rest.Data{
            Type:    "something",
            Content: someData,
        },
    }
    resp.WriteTo(w)
}

Output

{
  "code": 200,
  "message": "some helpful message",
  "data": {
    "something": {
      "hello": "world"
    }
  }
}

Respond with data and pagination

package handlers

import (
	"net/http"
	
	"github.com/LUSHDigital/core/pagination"
	"github.com/LUSHDigital/core/rest"
)

func someHandler(w http.ResponseWriter, r *http.Request) {
    someData := map[string]interface{}{
        "hello": "world",
    }
    
    preq := pagination.Request{
        PerPage: 10,
        Page:    1,
    }
    paginator := pagination.MakeResponse(preq, 100)
    resp := &rest.Response{
        Code:    http.StatusOK,
        Message: "some helpful message",
        Data: &rest.Data{
            Type:    "something",
            Content: someData,
        },
        Pagination: &paginator,
    }
    resp.WriteTo(w)
}

Output

{
  "code": 200,
  "message": "some helpful message",
  "data": {
    "something": {
      "hello": "world"
    }
  },
  "pagination": {
    "per_page": 10,
    "page": 1,
    "offset": 0,
    "total": 100,
    "last_page": 10
  }
}

Documentation

Overview

Package rest defines the how the default microservice response must look and behave like.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func UnmarshalJSONResponse

func UnmarshalJSONResponse(d []byte, dst interface{}) error

UnmarshalJSONResponse will unmarshal the data from legacy response envelope.

func WriteTo

func WriteTo(code int, i interface{}, w http.ResponseWriter) error

WriteTo writes any JSON response to a HTTP writer.

Types

type Data

type Data struct {
	Type    string
	Content interface{}
}

Data represents the collection data the the response will return to the consumer. Type ends up being the name of the key containing the collection of Content

func (*Data) MarshalJSON

func (d *Data) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface and is there to ensure the output is correct when we return data to the consumer

func (*Data) UnmarshalJSON

func (d *Data) UnmarshalJSON(b []byte) error

UnmarshalJSON implements the Unmarshaler interface this implementation will fill the type in the case we're been provided a valid single collection and set the content to the contents of said collection. for every other options, it behaves like normal. Despite the fact that we are not supposed to marshal without a type set, this is purposefully left open to unmarshal without a collection name set, in case you may want to set it later, and for interop with other systems which may not send the collection properly.

type EmptyResponse added in v0.16.0

type EmptyResponse struct{}

EmptyResponse is used to send no content to the API consumer.

func NoContentResponse added in v0.16.0

func NoContentResponse() *EmptyResponse

NoContentResponse returns a prepared 204 No Content response.

func (EmptyResponse) WriteTo added in v0.16.0

func (r EmptyResponse) WriteTo(w http.ResponseWriter) error

WriteTo writes a JSON response to a HTTP writer.

type Responder

type Responder interface {
	WriteTo(w http.ResponseWriter) error
}

Responder defines the behaviour of a response for JSON over HTTP. DEPRECATED: Responder interface should not be provided by the rest package.

type Response

type Response struct {
	Code       int                  `json:"code"`                 // Any valid HTTP response code
	Message    string               `json:"message"`              // Any relevant message (optional)
	Data       *Data                `json:"data,omitempty"`       // Data to pass along to the response (optional)
	Pagination *pagination.Response `json:"pagination,omitempty"` // Pagination data
}

Response defines a JSON response body over HTTP.

func BadRequestError added in v0.24.0

func BadRequestError(msg interface{}) *Response

BadRequestError returns a prepared 400 Bad Request Server Error, including the error message in the message field of the response object.

func ConflictErr

func ConflictErr(msg interface{}) *Response

ConflictErr returns a prepared 409 Conflict response, including the message passed by the user in the message field of the response object. DEPRECATED: Use ConflicError rather than ConflictErr TODO: Remove in version 1.x

func ConflictError added in v0.16.0

func ConflictError(msg interface{}) *Response

ConflictError returns a prepared 409 Conflict response, including the message passed by the user in the message field of the response object.

func CreatedResponse added in v0.16.0

func CreatedResponse(data *Data, page *pagination.Response) *Response

CreatedResponse returns a prepared 201 Created response.

func DBError

func DBError(msg interface{}) *Response

DBError returns a prepared 500 Internal Server Error response. DEPRECATED: Use InternalError rather than DBError TODO: Remove in version 1.x

func DBErrorf

func DBErrorf(format string, err error) *Response

DBErrorf returns a prepared 500 Internal Server Error response, using the user provided formatted message. DEPRECATED: Use InternalError rather than DBErrorf TODO: Remove in version 1.x

func Errorf added in v0.17.0

func Errorf(code int, format string, a ...interface{}) *Response

Errorf returns a prepared error response using the provided code and formatted message.

func InternalError

func InternalError(msg interface{}) *Response

InternalError returns a prepared 500 Internal Server Error, including the error message in the message field of the response object.

func JSONError

func JSONError(msg interface{}) *Response

JSONError returns a prepared 422 Unprocessable Entity response if the JSON is found to contain syntax errors, or invalid values for types.

func NotFoundErr

func NotFoundErr(msg interface{}) *Response

NotFoundErr returns a prepared 404 Not Found response, including the message passed by the user in the message field of the response object. DEPRECATED: Use NotFoundError rather than NotFoundErr TODO: Remove in version 1.x

func NotFoundError added in v0.16.0

func NotFoundError(msg interface{}) *Response

NotFoundError returns a prepared 404 Not Found response, including the message passed by the user in the message field of the response object.

func OKResponse added in v0.16.0

func OKResponse(data *Data, page *pagination.Response) *Response

OKResponse returns a prepared 200 OK response.

func ParamError

func ParamError(parameter string) *Response

ParamError returns a prepared 422 Unprocessable Entity response, including the name of the failing parameter in the message field of the response object. DEPRECATED: Use ParameterError rather than ParamError TODO: Remove in version 1.x

func ParameterError added in v0.16.0

func ParameterError(parameter string) *Response

ParameterError returns a prepared 422 Unprocessable Entity response, including the name of the failing parameter in the message field of the response object.

func Unauthorized added in v0.14.0

func Unauthorized() *Response

Unauthorized returns a prepared 401 Unauthorized error. DEPRECATED: Use UnauthorizedError rather than Unauthorized TODO: Remove in version 1.x

func UnauthorizedError added in v0.16.0

func UnauthorizedError() *Response

UnauthorizedError returns a prepared 401 Unauthorized error.

func ValidationError

func ValidationError(resource string, msg interface{}) *Response

ValidationError returns a prepared 422 Unprocessable Entity response, including the name of the failing validation/validator in the message field of the response object.

func (Response) WriteTo

func (r Response) WriteTo(w http.ResponseWriter) error

WriteTo writes a JSON response to a HTTP writer.

Jump to

Keyboard shortcuts

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