-
Notifications
You must be signed in to change notification settings - Fork 1
/
mockserver.go
86 lines (67 loc) · 1.57 KB
/
mockserver.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package mockserver
import (
"encoding/json"
"net/http"
"strconv"
"github.com/go-chi/chi"
)
func New() *MockServer {
return &MockServer{
pets: map[int]Pet{
1234: Pet{
Id: 1234,
Name: "doggie",
Category: PetCategory{
Id: 1,
Name: "Dogs",
},
Status: "available",
PhotoUrls: []string{},
},
},
}
}
type MockServer struct {
pets map[int]Pet
}
func (m *MockServer) Handler() http.Handler {
r := chi.NewRouter()
r.Use(defaultHeadersMiddleware)
r.Get("/pet/{petId}", func(w http.ResponseWriter, r *http.Request) {
petId, err := strconv.Atoi(chi.URLParamFromCtx(r.Context(), "petId"))
if err != nil {
sendJsonResponse(w, 500, err.Error())
return
}
pet, ok := m.pets[petId]
if !ok {
sendJsonResponse(w, 404, nil)
return
}
sendJsonResponse(w, 200, pet)
})
r.Delete("/pet/{petId}", func(w http.ResponseWriter, r *http.Request) {
petId, err := strconv.Atoi(chi.URLParamFromCtx(r.Context(), "petId"))
if err != nil {
sendJsonResponse(w, 500, err.Error())
return
}
delete(m.pets, petId)
sendJsonResponse(w, 204, nil)
})
return r
}
func (m *MockServer) SetPets(pets map[int]Pet) {
m.pets = pets
}
func sendJsonResponse(w http.ResponseWriter, statusCode int, body any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(body)
}
func defaultHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
next.ServeHTTP(w, r)
})
}