-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.go
More file actions
42 lines (35 loc) · 815 Bytes
/
response.go
File metadata and controls
42 lines (35 loc) · 815 Bytes
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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
type errorResponse struct {
Error string `json:"error,omitempty"`
}
func respondWithError(w http.ResponseWriter, code int, msg string) {
er := errorResponse{}
er.Error = msg
dat, err := json.Marshal(er)
if err != nil {
logMsg := fmt.Sprintf("Error marshalling JSON: %s", err)
log.Println(logMsg)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(logMsg))
return
}
w.WriteHeader(code)
w.Write(dat)
}
func respondWithJSON(w http.ResponseWriter, code int, payload any) {
dat, err := json.Marshal(payload)
if err != nil {
logMsg := fmt.Sprintf("Error marshalling JSON: %s", err)
log.Println(logMsg)
respondWithError(w, http.StatusInternalServerError, logMsg)
return
}
w.WriteHeader(code)
w.Write(dat)
}