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"}) }