/
httputils.go
53 lines (45 loc) · 1.2 KB
/
httputils.go
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
50
51
52
53
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type HttpResponseJson struct {
StatusCode int `json:"status_code"`
StatusTxt string `json:"status_txt"`
Data interface{} `json:"data"`
}
type MultiResult struct {
Key string `json:"key"`
Value string `json:"value"`
Status string `json:"status"`
Code int `json:"code"`
}
var (
ERROR_RESPONSE = `{"status_code": 500,"data": null,"status_txt": "COULD_NOT_FORMAT_RESULT"}`
)
func HttpError(w http.ResponseWriter, statusCode int, statusTxt string) bool {
w.WriteHeader(statusCode)
response := HttpResponseJson{StatusCode: statusCode, StatusTxt: statusTxt}
j, err := json.Marshal(response)
if err != nil {
fmt.Fprintf(w, ERROR_RESPONSE)
log.Printf("Could not format response: %s", err)
return false
}
fmt.Fprintf(w, "%s", j)
return true
}
func HttpResponse(w http.ResponseWriter, statusCode int, data interface{}) bool {
w.WriteHeader(statusCode)
response := HttpResponseJson{StatusCode: statusCode, Data: data}
j, err := json.Marshal(response)
if err != nil {
fmt.Fprintf(w, ERROR_RESPONSE)
log.Printf("Could not format response: %s", err)
return false
}
fmt.Fprintf(w, "%s", j)
return true
}