-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
52 lines (41 loc) · 1.16 KB
/
util.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
package server
import (
"encoding/json"
"fmt"
"net/http"
"github.com/go-chi/chi"
jsoniter "github.com/json-iterator/go"
)
/////////////////////////////////////////////////////////////
func getRequestVar(varname string, r *http.Request) string {
return chi.URLParam(r, varname)
}
func writeJSON(w http.ResponseWriter, contype string, content interface{}) *serverError {
var json = jsoniter.ConfigCompatibleWithStandardLibrary
encodedContent, err := json.Marshal(content)
if err != nil {
return serverErrorInternal(err, ErrMsgEncoding)
}
writeResponse(w, contype, encodedContent)
return nil
}
func writeResponse(w http.ResponseWriter, contype string, encodedContent []byte) {
w.Header().Set("Content-Type", contype)
w.WriteHeader(http.StatusOK)
w.Write(encodedContent)
}
func writeError(w http.ResponseWriter, status int, msg string) {
w.WriteHeader(status)
result, err := json.Marshal(struct {
Status int `json:"status"`
Description string `json:"description"`
}{
Status: status,
Description: msg,
})
if err != nil {
w.Write([]byte(fmt.Sprintf("error fallback: unable to marshal error message: %v", msg)))
return
}
w.Write(result)
}