api

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2022 License: MIT Imports: 3 Imported by: 4

README

API

Concise library for generating API responses in JSON format

Shortcut methods

  • Error(msg string)
  • ErrorWithData(msg string, data []interface)
  • Forbidden(msg string)
  • Success(msg string)
  • SuccessWithData(msg string, data []interface)
  • Unauthenticated(msg string)
  • Unauthorized(msg string)

Example

// return error response
api.Respond(w, r, api.Error("api key is required"))

// return success response with data payload
api.Respond(w, r, api.SuccessWithData("success", map[string]interface{}{
  "key1": "value1",
  "key2": "value1",
  "key3": "value1",
}))

Custom responses

api.Respond(w, r, api.Response{
  Status:  "custom_status",
  Message: "message",
  Data: map[string]interface{}{
    "key1": "value1",
    "key2": "value1",
    "key3": "value1",
  },
})

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Respond

func Respond(w http.ResponseWriter, r *http.Request, resp Response)

Respond writes a JSON or JSONP response

func RespondWithStatus added in v1.5.0

func RespondWithStatus(w http.ResponseWriter, r *http.Request, resp Response, status int)

Respond writes a JSON or JSONP response

Types

type Response

type Response struct {
	Status  string                 `json:"status"`
	Message string                 `json:"message"`
	Data    map[string]interface{} `json:"data"`
}

Response defines an response for the API

func Error

func Error(message string) Response

Error returns an error message

func ErrorWithData

func ErrorWithData(message string, data map[string]interface{}) Response

ErrorWithData returns an error message with data

func Forbidden added in v1.2.0

func Forbidden(message string) Response

Forbidden returns an forbidden message, user is authenticated but insufficient permissions

func Success

func Success(message string) Response

Success returns a success message

func SuccessWithData

func SuccessWithData(message string, data map[string]interface{}) Response

SuccessWithData returns a success message with data

func Unauthenticated added in v1.4.0

func Unauthenticated(message string) Response

Unauthenticated returns an unauthenticated message, user is not known (authenticated)

func Unauthorized added in v1.2.0

func Unauthorized(message string) Response

Unauthorized returns an unauthorized message, user is known but not unauthorized to do the action

func (Response) ToString added in v1.3.0

func (r Response) ToString() string

Jump to

Keyboard shortcuts

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