-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
171 lines (124 loc) · 3.5 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/Calvisd/autocomplete/search"
)
type RecommendationResponse struct {
Recommendations []string `json:"recommendations"`
}
type SearchResponse struct {
Found bool `json:"found"`
}
func main() {
var interruptSignal = make(chan bool)
go handleShutdowns(interruptSignal)
// Initialize datastore
dataStore := search.NewDataStore()
dataStore.InitializeDataStore()
//Web Interface
const port string = ":8080"
var serverShutdownSignal = make(chan bool)
mux := http.NewServeMux()
mux.HandleFunc("/", homePage)
mux.HandleFunc("/search/recommendations", recommendData(dataStore))
mux.HandleFunc("/search", searchData(dataStore))
// server config
server := http.Server{
Addr: port,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 30 * time.Second,
Handler: mux,
}
go func() {
fmt.Println("Started server on port:", port)
err := server.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatal("Error starting the server", err)
}
fmt.Println("Shutting down server...")
serverShutdownSignal <- true
}()
<-interruptSignal
// Create a context with a timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Shutdown the server gracefully
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Server shutdown failed: %v\n", err)
}
<-serverShutdownSignal
}
// home page reqest handler
func homePage(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("404 PAGE NOT FOUND"))
return
}
http.ServeFile(w, r, "./index.html")
}
// search request handler
func searchData(dataStore *search.DataStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := r.URL.Query()["q"]; r.Method != http.MethodGet || !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Bad Request"))
return
}
result := dataStore.Search(r.URL.Query()["q"][0])
response := SearchResponse{
Found: result.Found,
}
serializedResponse, err := json.Marshal(response)
if err != nil {
log.Fatal("Error serializing response", err)
}
w.WriteHeader(http.StatusOK)
w.Write(serializedResponse)
}
}
// Recommendation request handler
func recommendData(dataStore *search.DataStore) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if _, ok := r.URL.Query()["q"]; r.Method != http.MethodGet || !ok {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("Bad Request"))
return
}
result := dataStore.Search(r.URL.Query()["q"][0])
response := RecommendationResponse{
Recommendations: result.Recommendations,
}
serializedResponse, err := json.Marshal(response)
if err != nil {
log.Fatal("Error serializing response", err)
}
w.WriteHeader(http.StatusOK)
w.Write(serializedResponse)
}
}
// listens for shutdown signals
func handleShutdowns(done chan<- bool) {
signalChannel := make(chan os.Signal, 2)
signal.Notify(signalChannel, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGSEGV)
go func() {
sig := <-signalChannel
switch sig {
case os.Interrupt:
log.Println("Encountered os interrupt")
done <- true
case syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGINT, syscall.SIGSEGV:
log.Println("Received linux signel")
done <- true
}
}()
}