-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
226 lines (185 loc) · 4.72 KB
/
main.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
package main
import (
"encoding/json"
"log"
"math/rand"
"net/http"
"time"
"fmt"
"github.com/gorilla/mux"
// "math/rand"
"strconv"
)
type MutateMovieBody struct {
ISBN string `json:"isbn"`
Title string `json:"title"`
Director *Director `json:"director"`
}
type Movie struct {
Id string `json:"id"`
ISBN string `json:"isbn"`
Title string `json:"title"`
Director *Director `json:"director"`
}
type Director struct {
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
}
var movies []Movie
type Error struct {
Message string
}
type DeleteMovieByIdResponse struct {
Movies []Movie
Movie Movie
Index int
}
type AddMovieResponse struct {
Movies []Movie
}
func catchErrors() {
if err := recover(); err != nil {
log.Println(err)
}
}
func getMovies(w http.ResponseWriter, r *http.Request) {
defer catchErrors()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(movies)
}
func getMovieById(w http.ResponseWriter, r *http.Request) {
defer catchErrors()
w.Header().Set("Content-Type", "application/json")
id := mux.Vars(r)["id"]
var movie Movie
for _, m := range movies {
if m.Id == id {
fmt.Println("if m.Id == id", m)
movie = m
break
}
}
if movie == (Movie{}) {
fmt.Println("error")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(Error{Message: "Not found!"})
} else {
fmt.Println("response")
json.NewEncoder(w).Encode(movie)
}
}
func deleteMovieById(w http.ResponseWriter, r *http.Request) {
defer catchErrors()
w.Header().Set("Content-Type", "application/json")
id := mux.Vars(r)["id"]
idAsInteger, err := strconv.ParseUint(id, 10, 32)
if err != nil || idAsInteger <= 0 {
w.WriteHeader(400)
json.NewEncoder(w).Encode(Error{Message: "Invalid Id!"})
return
}
var filteredMovies []Movie
index := -1
for i, m := range movies {
if m.Id == id {
index = i
} else {
filteredMovies = append(filteredMovies, m)
}
}
if index == -1 {
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(Error{Message: "Not found!"})
return
} else {
movie := movies[index]
movies = filteredMovies
json.NewEncoder(w).Encode(DeleteMovieByIdResponse{
Movies: filteredMovies,
Movie: movie,
Index: index,
})
}
}
func getRandomId() string {
s1 := rand.NewSource(time.Now().UnixNano())
r1 := rand.New(s1)
randomId := r1.Intn(100)
randomIdAsString := strconv.Itoa(randomId)
return randomIdAsString
}
func addMovie(w http.ResponseWriter, r *http.Request) {
defer catchErrors()
w.Header().Set("Content-Type:", "application/json")
var movie MutateMovieBody
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
err := decoder.Decode(&movie)
if err != nil {
w.WriteHeader(400)
json.NewEncoder(w).Encode(Error{Message: "Invalid arguments!"})
return
}
isbn := movie.ISBN
title := movie.Title
directorFirstName := movie.Director.Firstname
directorLastname := movie.Director.Lastname
if title == "" || directorFirstName == "" || directorLastname == "" {
w.WriteHeader(400)
json.NewEncoder(w).Encode(Error{Message: "Invalid arguments!"})
return
} else {
Id := getRandomId()
movies = append(movies, Movie{
Id: Id,
ISBN: isbn,
Title: title,
Director: &Director{
Firstname: directorFirstName,
Lastname: directorLastname,
},
})
json.NewEncoder(w).Encode(AddMovieResponse{Movies: movies})
}
}
func updateMovie(w http.ResponseWriter, r *http.Request) {
defer catchErrors()
w.Header().Set("Content-Type:", "application/json")
var movie Movie
id := mux.Vars(r)["id"]
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&movie)
decoder.DisallowUnknownFields()
if err != nil {
w.WriteHeader(400)
json.NewEncoder(w).Encode(Error{Message: "Invalid arguments"})
return
}
if movie.Title == "" || movie.Director.Firstname == "" || movie.Director.Lastname == "" || movie.ISBN == "" {
w.WriteHeader(400)
json.NewEncoder(w).Encode(Error{Message: "Invalid arguments!"})
return
}
var index int
for i, oldMovie := range movies {
if id == oldMovie.Id {
index = i
break
}
}
movie.Id = movies[index].Id
movies = append(movies[:index], movies[index+1:]...)
movies = append(movies, movie)
json.NewEncoder(w).Encode(AddMovieResponse{Movies: movies})
}
func main() {
router := mux.NewRouter()
movies = addDummyData(movies)
router.HandleFunc("/movies", getMovies).Methods("GET")
router.HandleFunc("/movies/{id}", getMovieById).Methods("GET")
router.HandleFunc("/movies/{id}", deleteMovieById).Methods("DELETE")
router.HandleFunc("/movies", addMovie).Methods("POST")
router.HandleFunc("/movies/{id}", updateMovie).Methods("PUT")
fmt.Println("Starting server on port 8000")
log.Fatal(http.ListenAndServe(":8000", router))
}