jsend

package module
v0.0.0-...-72b842f Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2018 License: MIT Imports: 2 Imported by: 0

README

jsend

jsend is a Go package that implements the JSend specification.

Installation

go get github.com/joaodlf/jsend

(no dependencies required)

Usage

Simply pass a http.ResponseWriter to jsend.Write(). You can also pass a list of options to tailor your output:

jsend.Write(w,
    jsend.Data(map[string]interface{}{
        "user_id": 1,
        "email": "you@domain.com",
    }),
)

The above will output the following JSON encoded message:

{
    data: {
        email: "you@domain.com",
        user_id: 1
    },
    status: "success"
}

Example

package main

import (
	"github.com/joaodlf/jsend"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		jsend.Write(w,
			jsend.Data(map[string]interface{}{
				"user_id": 1,
				"email": "you@domain.com",
			}),
		)
	})

	http.HandleFunc("/fail", func(w http.ResponseWriter, r *http.Request) {
		jsend.Write(w,
			jsend.StatusCode(400),
			jsend.Data(map[string]interface{}{
				"fail": true,
			}),
		)
	})

	http.HandleFunc("/error", func(w http.ResponseWriter, r *http.Request) {
		jsend.Write(w,
			jsend.StatusCode(500),
			jsend.Message("Error! (The 'code' and 'data' fields are optional here)"),
			jsend.Code(1),
			jsend.Data(map[string]interface{}{
				"error": true,
			}),
		)
	})

	http.ListenAndServe(":8001", nil)
}

Documentation

Overview

Package jsend implements the JSend specification (https://labs.omniti.com/labs/jsend).

Index

Constants

View Source
const (
	StatusSuccess = "success"
	StatusError   = "error"
	StatusFail    = "fail"
)

Variables

This section is empty.

Functions

func Code

func Code(c int) func(*jsendResponse)

Code is a functional option that sets the code field

func Data

func Data(d map[string]interface{}) func(*jsendResponse)

Data is a functional option that sets the data field.

func Message

func Message(m string) func(*jsendResponse)

Message is a functional option that sets the message field.

func StatusCode

func StatusCode(c int) func(*jsendResponse)

StatusCode is a functional option that sets the status code to be used in the HTTP response.

func Write

func Write(w http.ResponseWriter, options ...func(*jsendResponse)) (int, error)

Write writes a JSON encoded message that satisfies the JSend specification. Besides receiving an http.ResponseWriter, it also receives functional options to set the various JSend fields.

Types

This section is empty.

Jump to

Keyboard shortcuts

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