-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
117 lines (97 loc) · 2.29 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
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"log"
"math/rand"
"net/http"
"strconv"
)
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
func init() {
movies = append(movies, Movie{
ID: "1",
Isbn: "1234",
Title: "Movie 1",
Director: &Director{
FirstName: "John",
LastName: "Doe",
},
})
movies = append(movies, Movie{
ID: "2",
Isbn: "1235",
Title: "Movie 2",
Director: &Director{
FirstName: "Jane",
LastName: "Doe",
},
})
}
func main() {
r := mux.NewRouter()
r.Use(headerMiddleware)
r.HandleFunc("/movies", getMovies).Methods("GET")
r.HandleFunc("/movies/{id}", getMovie).Methods("GET")
r.HandleFunc("/movies", createMovie).Methods("POST")
r.HandleFunc("/movies/{id}", updateMovie).Methods("PUT")
r.HandleFunc("/movies/{id}", deleteMovie).Methods("DELETE")
fmt.Println("starting server at port 8080")
if err := http.ListenAndServe(":8080", r); err != nil {
log.Fatal(err)
}
}
func updateMovie(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
for index, movie := range movies {
if movie.ID == id {
movies = append(movies[:index], movies[index+1:]...)
var movie Movie
_ = json.NewDecoder(r.Body).Decode(&movie)
movie.ID = id
movies = append(movies, movie)
json.NewEncoder(w).Encode(movie)
return
}
}
}
func createMovie(w http.ResponseWriter, r *http.Request) {
var movie Movie
_ = json.NewDecoder(r.Body).Decode(&movie)
movie.ID = strconv.Itoa(rand.Intn(100000))
movies = append(movies, movie)
json.NewEncoder(w).Encode(movie)
}
func getMovie(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
for _, movie := range movies {
if movie.ID == id {
json.NewEncoder(w).Encode(movie)
return
}
}
}
func deleteMovie(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
for index, movie := range movies {
if movie.ID == id {
movies = append(movies[:index], movies[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(movies)
}
func getMovies(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(movies)
}