aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/http_util.go
diff options
context:
space:
mode:
Diffstat (limited to 'cmd/web/http_util.go')
-rw-r--r--cmd/web/http_util.go49
1 files changed, 49 insertions, 0 deletions
diff --git a/cmd/web/http_util.go b/cmd/web/http_util.go
new file mode 100644
index 0000000..941e270
--- /dev/null
+++ b/cmd/web/http_util.go
@@ -0,0 +1,49 @@
+package main
+
+import (
+ "encoding/json"
+ "net/http"
+)
+
+type respStatus struct {
+ Status string `json:"status" example:"OK"`
+}
+
+type respError struct {
+ Error string `json:"error" example:"Descriptive Error message"`
+}
+
+// HttpJSONResp will return a JSON response down to the client, setting
+// the appropriate content-type header and the status code provided.
+// optionally if "logmsg" is not empty it will log that string
+func HttpJSONResp(
+ w http.ResponseWriter, r *http.Request,
+ StatusCode int, logmsg string, data interface{}) {
+ w.Header().Add("Content-type", "application/json")
+ w.WriteHeader(StatusCode)
+
+ if logmsg != "" {
+ Logger.Printf("%s : %s", r.URL.Path, logmsg)
+ }
+
+ enc := json.NewEncoder(w)
+ err := enc.Encode(data)
+ if err != nil {
+ Logger.Printf("%s ERROR: %s", r.URL.Path, err)
+ }
+}
+
+// HttpJSONRespErr just calls HttpJSONResp with a
+// map[string]string{"error": respmsg}
+// as the data
+func HttpJSONRespErr(
+ w http.ResponseWriter, r *http.Request,
+ StatusCode int, logmsg, respmsg string) {
+ HttpJSONResp(w, r, StatusCode,
+ logmsg, &respError{Error: respmsg})
+}
+
+// HttpJSONOK simply returns json encoded {"status": "ok"} down to the client
+func HttpJSONOK(w http.ResponseWriter, r *http.Request, logmsg string) {
+ HttpJSONResp(w, r, http.StatusOK, logmsg, &respStatus{Status: "OK"})
+}