moth/pkg/jsend/jsend.go

60 lines
1.7 KiB
Go
Raw Normal View History

2020-08-17 17:43:57 -06:00
package jsend
2020-02-29 18:36:59 -07:00
import (
"encoding/json"
"fmt"
"net/http"
)
// This provides a JSend function for MOTH
// https://github.com/omniti-labs/jsend
const (
2020-08-17 17:43:57 -06:00
// Success is the return code indicating "All went well, and (usually) some data was returned".
Success = "success"
// 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".
Fail = "fail"
// Error is the return code indicating "An error occurred in processing the request, i.e. an exception was thrown".
Error = "error"
2020-02-29 18:36:59 -07:00
)
2020-08-17 17:43:57 -06:00
// JSONWrite writes out data as JSON, sending headers and content length
2020-02-29 18:36:59 -07:00
func JSONWrite(w http.ResponseWriter, data interface{}) {
respBytes, err := json.Marshal(data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2020-02-29 22:37:22 -07:00
2020-02-29 18:36:59 -07:00
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(respBytes)))
w.WriteHeader(http.StatusOK) // RFC2616 makes it pretty clear that 4xx codes are for the user-agent
w.Write(respBytes)
}
2020-08-17 17:43:57 -06:00
// Send sends arbitrary data as a JSend response
func Send(w http.ResponseWriter, status string, data interface{}) {
2020-02-29 22:37:22 -07:00
resp := struct {
Status string `json:"status"`
2020-02-29 18:36:59 -07:00
Data interface{} `json:"data"`
}{}
resp.Status = status
resp.Data = data
JSONWrite(w, resp)
}
2020-08-17 17:43:57 -06:00
// Sendf sends a Sprintf()-formatted string as a JSend response
func Sendf(w http.ResponseWriter, status, short string, format string, a ...interface{}) {
2020-02-29 22:37:22 -07:00
data := struct {
2020-02-29 18:36:59 -07:00
Short string `json:"short"`
Description string `json:"description"`
}{}
data.Short = short
data.Description = fmt.Sprintf(format, a...)
2020-02-29 22:37:22 -07:00
2020-08-17 17:43:57 -06:00
Send(w, status, data)
2020-02-29 18:36:59 -07:00
}