aboutsummaryrefslogtreecommitdiff
path: root/cmd/web/http_util.go
blob: 941e270c5d90118dcd09a4f27fa0696462bf3f97 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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"})
}