-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
46 lines (38 loc) · 972 Bytes
/
helpers.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
package main
import (
"encoding/json"
"log"
"net/http"
)
func writeError(w http.ResponseWriter, code int, error string) {
type responseError struct {
Error string `json:"error"`
}
respError := responseError{}
w.WriteHeader(code)
respError.Error = error
dat, err := json.Marshal(respError)
if err != nil {
log.Printf("Error marshalling JSON: %s", err)
write500Error(w)
return
}
w.Write(dat)
}
func write500Error(w http.ResponseWriter) {
writeError(w, 500, "Something went wrong")
}
func writeJSONResponse(w http.ResponseWriter, statusCode int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
response, err := json.Marshal(data)
if err != nil {
log.Printf("Error marshalling JSON: %s", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
_, writeErr := w.Write(response)
if writeErr != nil {
log.Printf("Error writing response: %s", writeErr)
}
}