-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponses.go
53 lines (45 loc) · 1.07 KB
/
responses.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"
"log"
"net/http"
)
type parameters struct {
Body string `json:"body"`
UserID string `json:"user_id"`
}
type returnVals struct {
Error string `json:"error"`
}
type chirpData struct {
ID string `json:"id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
Body string `json:"body"`
UserID string `json:"user_id"`
}
func respondWithError(w http.ResponseWriter, code int, msg string) {
retVals := returnVals{
Error: msg,
}
data, err := json.Marshal(retVals)
if err != nil {
log.Printf("Error marshalling JSON: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(data)
}
func respondWithJSON(w http.ResponseWriter, code int, payload any) {
data, err := json.Marshal(payload)
if err != nil {
log.Printf("Error marshalling JSON: %s", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(data)
}