-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
74 lines (60 loc) · 1.73 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
package main
import (
"encoding/json"
"log"
"net/http"
)
const PORT string = ":4000"
func main() {
http.HandleFunc("/", homeHandler)
http.HandleFunc("/404", NotFoundHandler)
http.HandleFunc("/ping", pingHandler)
http.HandleFunc("/pong", pongHandler)
log.Println("Server started listening on port ", PORT)
http.ListenAndServe(PORT, nil)
}
func homeHandler(w http.ResponseWriter, r *http.Request) {
response := map[string]string{"hello": "world"}
jsonResponse, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonResponse)
}
func pingHandler(w http.ResponseWriter, _ *http.Request) {
response := map[string]string{
"Message": "Pong",
}
jsonResponse, err := json.MarshalIndent(response, "", "2")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonResponse)
}
func pongHandler(w http.ResponseWriter, _ *http.Request) {
response := map[string]string{
"Message": "Ping",
}
jsonResponse, err := json.MarshalIndent(response, "", "2")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(jsonResponse)
}
func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
response := map[string]string{"error": "404- Not found"}
jsonResponse, err := json.Marshal(response)
if err != nil {
log.Println("failed to marshal json")
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
w.Write(jsonResponse)
}