-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
68 lines (60 loc) · 1.96 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)
type Movie struct {
ID string `json:id`
Ishon string `json:ishon`
Title string `json:title`
Director *Director `json:director`
}
type Director struct {
Firstname string `json:firstname`
Lasttname string `json:lastname`
}
var movies []Movie
func getMovies(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(movies)
}
func deleteMovie(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for index, item := range movies {
if item.ID == params["id"] {
movies = append(movies[:index], movies[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(movies)
}
func getMovie(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
params := mux.Vars(r)
for _, v := range movies {
if v.ID == params["id"] {
json.NewEncoder(w).Encode(v)
}
}
}
func createMovie(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
movies = append(movies, Movie{ID: "3", Ishon: "455343", Title: "Move three", Director: &Director{Firstname: "Ben", Lasttname: "Simens"}})
json.NewEncoder(w).Encode(movies)
}
func main() {
r := mux.NewRouter()
movies = append(movies, Movie{ID: "1", Ishon: "4343", Title: "Move one", Director: &Director{Firstname: "John", Lasttname: "Doe"}})
movies = append(movies, Movie{ID: "2", Ishon: "3432", Title: "Move two", Director: &Director{Firstname: "Steve", Lasttname: "Smith"}})
r.HandleFunc("/movies", getMovies).Methods("GET")
r.HandleFunc("/movies/{id}", getMovie).Methods("GET")
r.HandleFunc("/createMovie", createMovie).Methods("GET")
//r.HandleFunc("/movies/{id}",updateMovie).Methods("PUT")
r.HandleFunc("/movies/{id}", deleteMovie).Methods("DELETE")
fmt.Printf("hello world go server")
log.Fatal(http.ListenAndServe(":8080", r))
}