-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
63 lines (52 loc) · 1.51 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
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/proishan11/data-collection-tree/models"
"github.com/proishan11/data-collection-tree/tree"
"github.com/proishan11/data-collection-tree/utils"
"net/http"
)
var (
t = tree.NewTree()
)
func insertHandler(response http.ResponseWriter, req *http.Request) {
response.Header().Set("Content-type", "application/json")
var reqBody models.Request
err := json.NewDecoder(req.Body).Decode(&reqBody)
if err == nil {
node := reqBody.Serialize()
t.Insert(node)
fmt.Println("Successfully inserted")
response.WriteHeader(http.StatusOK)
} else {
response.WriteHeader(http.StatusInternalServerError)
fmt.Println("Some error occurred ", err)
}
}
func queryHandler(response http.ResponseWriter, req *http.Request) {
response.Header().Set("Content-type", "application/json")
var reqBody models.Query
err := json.NewDecoder(req.Body).Decode(&reqBody)
if err == nil {
fmt.Println(reqBody.GetCountry())
node := t.FindByCountry(reqBody.GetCountry())
if node != nil {
res := utils.ResponseFromNode(*node)
response.WriteHeader(http.StatusOK)
json.NewEncoder(response).Encode(res)
} else {
response.WriteHeader(http.StatusOK)
}
} else {
response.WriteHeader(http.StatusInternalServerError)
}
}
func main() {
const port string = ":8000"
router := mux.NewRouter()
router.HandleFunc("/v1/insert", insertHandler).Methods("POST")
router.HandleFunc("/v1/query", queryHandler).Methods("GET")
http.ListenAndServe(port, router)
}