From 0fc3eda77004f41c5f0a804028da2d90b0373ea7 Mon Sep 17 00:00:00 2001 From: Mitchell Riedstra Date: Tue, 24 Aug 2021 22:25:40 -0400 Subject: Another development snapshot. Updated license. Added Swagger documentation--embedded! Note about 'swaggo' --- cmd/web/http_util.go | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 cmd/web/http_util.go (limited to 'cmd/web/http_util.go') 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"}) +} -- cgit v1.2.3