-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheventhandler.go
96 lines (85 loc) · 2.44 KB
/
eventhandler.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
package main
import (
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/gorilla/mux"
"github.com/taha-ahmadi/iEvents/persistence"
"go.mongodb.org/mongo-driver/bson/primitive"
)
type eventServiceHandler struct {
dbhandler persistence.DatabaseHandler
}
func NewEventHandler(databasehandler persistence.DatabaseHandler) *eventServiceHandler {
return &eventServiceHandler{
dbhandler: databasehandler,
}
}
func (eh *eventServiceHandler) FindEventHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
criteria, ok := vars["SearchCriteria"]
if !ok {
w.WriteHeader(400)
fmt.Fprint(w, `{"error": "No search criteria found, you can either
search by id via /id/4
to search by name via /name/coldplayconcert}"`)
return
}
searchkey, ok := vars["search"]
if !ok {
w.WriteHeader(400)
fmt.Fprint(w, `{"error": "No search keys found, you can either search
by id via /id/4
to search by name via /name/coldplayconcert}"`)
return
}
var event persistence.Event
var err error
switch strings.ToLower(criteria) {
case "name":
event, err = eh.dbhandler.FindEventByName(searchkey)
case "id":
id, err := hex.DecodeString(searchkey)
if err == nil {
event, err = eh.dbhandler.FindEvent(id)
}
}
if err != nil {
fmt.Fprintf(w, `{"error": "%s"}`, err)
return
}
w.Header().Set("Content-Type", "application/json;charset=utf8")
json.NewEncoder(w).Encode(&event)
}
func (eh *eventServiceHandler) AllEventHandler(w http.ResponseWriter, r *http.Request) {
events, err := eh.dbhandler.FindAllAvailableEvents()
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, `{"error": "Error occured while trying to find all available events %s"}`, err)
return
}
w.Header().Set("Content-Type", "application/json;charset=utf8")
err = json.NewEncoder(w).Encode(&events)
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, `{"error": "Error occured while trying encode events to JSON %s"}`, err)
}
}
func (eh *eventServiceHandler) NewEventHandler(w http.ResponseWriter, r *http.Request) {
event := persistence.Event{}
err := json.NewDecoder(r.Body).Decode(&event)
if nil != err {
w.WriteHeader(500)
fmt.Fprintf(w, `{"error": "error occured while decoding event data %s"}`, err)
return
}
event.ID = primitive.NewObjectID()
id, err := eh.dbhandler.AddEvent(event)
if nil != err {
w.WriteHeader(500)
fmt.Fprintf(w, `{"error": "error occured while persisting event %d %s"}`, id, err)
return
}
}