aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/http_util.go
diff options
context:
space:
mode:
authorMitchell Riedstra <mitch@riedstra.dev>2021-08-24 22:25:40 -0400
committerMitchell Riedstra <mitch@riedstra.dev>2021-08-24 22:25:40 -0400
commit0fc3eda77004f41c5f0a804028da2d90b0373ea7 (patch)
treeedf6d74e6a2b7140350eab1e40d0fbf70e10f87c /cmd/web/http_util.go
parentf4fcd237b2d0eb950fc15a8af1fb0894b6ad6359 (diff)
downloadsteam-export-0fc3eda77004f41c5f0a804028da2d90b0373ea7.tar.gz
steam-export-0fc3eda77004f41c5f0a804028da2d90b0373ea7.tar.xz
Another development snapshot. Updated license. Added Swagger documentation--embedded! Note about 'swaggo'
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"})
+}