-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
91 lines (77 loc) · 2.32 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
package main
import (
"encoding/json"
"fmt"
"log"
"math/rand"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
type Ticket struct {
ID string `json:"id"`
Isbn string `json:"Isbn"`
Name string `json:"name"`
Price int `json:"price"`
}
var tickets []Ticket
func main() {
tickets = append(tickets, Ticket{ID: "1", Isbn: "9009", Name: "Astana", Price: 15000})
tickets = append(tickets, Ticket{ID: "2", Isbn: "4508", Name: "Moscow", Price: 22000})
request := mux.NewRouter()
request.HandleFunc("/tickets", getTickets).Methods("GET")
request.HandleFunc("/tickets/{id}", getTicket).Methods("GET")
request.HandleFunc("/tickets", createTicket).Methods("POST")
request.HandleFunc("/tickets/{id}", updateTicket).Methods("PUT")
request.HandleFunc("/tickets/{id}", deleteTicket).Methods("DELETE")
fmt.Printf("Server started at port 8080\n")
log.Fatal(http.ListenAndServe(":8080", request))
}
func getTickets(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
json.NewEncoder(w).Encode(tickets)
}
func getTicket(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
params := mux.Vars(r)
for _, item := range tickets {
if item.ID == params["id"] {
json.NewEncoder(w).Encode(item)
return
}
}
}
func createTicket(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
var ticket Ticket
_ = json.NewDecoder(r.Body).Decode(&ticket)
ticket.ID = strconv.Itoa(rand.Intn(10000))
tickets = append(tickets, ticket)
json.NewEncoder(w).Encode(ticket)
}
func updateTicket(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
params := mux.Vars(r)
for index, item := range tickets {
if item.ID == params["id"] {
tickets = append(tickets[:index], tickets[index+1:]...)
var ticket Ticket
_ = json.NewDecoder(r.Body).Decode(&ticket)
ticket.ID = params["id"]
tickets = append(tickets, ticket)
json.NewEncoder(w).Encode(ticket)
return
}
}
}
func deleteTicket(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
params := mux.Vars(r)
for index, item := range tickets {
if item.ID == params["id"] {
tickets = append(tickets[:index], tickets[index+1:]...)
break
}
}
json.NewEncoder(w).Encode(tickets)
}