moth

Monarch Of The Hill game server
git clone https://git.woozle.org/neale/moth.git

moth / pkg / jsend
Neale Pickett  ·  2020-08-17

jsend.go

 1package jsend
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"net/http"
 7)
 8
 9// This provides a JSend function for MOTH
10// https://github.com/omniti-labs/jsend
11
12const (
13	// Success is the return code indicating "All went well, and (usually) some data was returned".
14	Success = "success"
15
16	// Fail is the return code indicating "There was a problem with the data submitted, or some pre-condition of the API call wasn't satisfied".
17	Fail = "fail"
18
19	// Error is the return code indicating "An error occurred in processing the request, i.e. an exception was thrown".
20	Error = "error"
21)
22
23// JSONWrite writes out data as JSON, sending headers and content length
24func JSONWrite(w http.ResponseWriter, data interface{}) {
25	respBytes, err := json.Marshal(data)
26	if err != nil {
27		http.Error(w, err.Error(), http.StatusInternalServerError)
28		return
29	}
30
31	w.Header().Set("Content-Type", "application/json")
32	w.Header().Set("Content-Length", fmt.Sprintf("%d", len(respBytes)))
33	w.WriteHeader(http.StatusOK) // RFC2616 makes it pretty clear that 4xx codes are for the user-agent
34	w.Write(respBytes)
35}
36
37// Send sends arbitrary data as a JSend response
38func Send(w http.ResponseWriter, status string, data interface{}) {
39	resp := struct {
40		Status string      `json:"status"`
41		Data   interface{} `json:"data"`
42	}{}
43	resp.Status = status
44	resp.Data = data
45
46	JSONWrite(w, resp)
47}
48
49// Sendf sends a Sprintf()-formatted string as a JSend response
50func Sendf(w http.ResponseWriter, status, short string, format string, a ...interface{}) {
51	data := struct {
52		Short       string `json:"short"`
53		Description string `json:"description"`
54	}{}
55	data.Short = short
56	data.Description = fmt.Sprintf(format, a...)
57
58	Send(w, status, data)
59}