-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
78 lines (64 loc) · 1.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/gorilla/mux"
)
type event struct {
ID string `json:"ID"`
Title string `json:"Title"`
Description string `json:"Description"`
}
type allEvents []event
var events = allEvents{
{
ID: "1",
Title: "Golang rocks",
Description: "init server",
},
}
var eventtwo = allEvents{
{
ID: "2",
Title: "Second event",
Description: "testing values",
},
}
func homeLink(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome home!")
}
func createEvent(w http.ResponseWriter, r *http.Request) {
var newEvent event
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
fmt.Fprintf(w, "Kindly enter data with the event id, title and description only in order to update")
}
json.Unmarshal(reqBody, &newEvent)
events = append(events, newEvent)
events = append(events, eventtwo...)
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newEvent)
}
func getOneEvent(w http.ResponseWriter, r *http.Request) {
eventID := mux.Vars(r)["id"]
for _, singleEvent := range events {
if singleEvent.ID == eventID {
json.NewEncoder(w).Encode(singleEvent)
}
}
}
func getAllEvents(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(events)
}
#have to add functionalties to main file
func main() {
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", homeLink)
router.HandleFunc("/event", createEvent).Methods("POST")
router.HandleFunc("/events", getAllEvents).Methods("GET")
router.HandleFunc("/events/{id}", getOneEvent).Methods("GET")
log.Fatal(http.ListenAndServe(":3007", router)) // execute lsof -i:"port number" ,followed by kill -9 "pid of the app"
}