This repository has been archived by the owner on Jan 26, 2022. It is now read-only.
/
server_http.go
206 lines (180 loc) · 4.63 KB
/
server_http.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package ekanite
import (
"fmt"
"html/template"
"log"
"net"
"net/http"
"os"
"time"
)
// HTTPServer serves query client connections.
type HTTPServer struct {
iface string
Searcher Searcher
addr net.Addr
template *template.Template
Logger *log.Logger
}
// NewHTTPServer returns a new Server instance.
func NewHTTPServer(iface string, searcher Searcher) *HTTPServer {
return &HTTPServer{
iface: iface,
Searcher: searcher,
Logger: log.New(os.Stderr, "[httpserver] ", log.LstdFlags),
}
}
// Start instructs the Server to bind to the interface and accept connections.
func (s *HTTPServer) Start() error {
ln, err := net.Listen("tcp", s.iface)
if err != nil {
return err
}
s.addr = ln.Addr()
s.template, err = template.New("ServerTemplate").Parse(templateSource)
if err != nil {
ln.Close()
return err
}
go http.Serve(ln, s)
return nil
}
// Addr returns the address to which the Server is bound.
func (s *HTTPServer) Addr() net.Addr {
return s.addr
}
// ServeHTTP implements a http.Handler, serving the query interface for Ekanite
func (s *HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
dontCache(w, r)
if r.Method == "GET" || r.Method == "HEAD" {
// HEAD is conveniently supported by net/http without further action
err := serveIndex(s, w, r)
if err != nil {
s.Logger.Print("Error executing template: ", err)
http.Error(w, "Error executing template: "+err.Error(), http.StatusInternalServerError)
return
}
} else if r.Method == "POST" {
err := r.ParseForm()
if err != nil {
s.Logger.Printf("Error parsing form '%s'", err)
http.Error(w, "Error parsing form", http.StatusBadRequest)
return
}
if len(r.FormValue("query")) == 0 {
serveIndex(s, w, r)
return
}
userQuery := r.FormValue("query")
s.Logger.Printf("executing query '%s'", userQuery)
start := time.Now()
resultSet, err := s.Searcher.Search(userQuery)
dur := time.Since(start)
var resultSlice []string
if err != nil {
s.Logger.Printf("Error executing query: '%s'", err)
http.Error(w, "Error executing query: "+err.Error(), http.StatusInternalServerError)
return
}
for s := range resultSet {
resultSlice = append(resultSlice, s)
}
data := struct {
Title string
Headline string
ReturnResults bool
LogMessages []string
}{
"Ekanite query interface",
fmt.Sprintf(`Ekanite - Listing %d results for "%s" (%s)`, len(resultSlice), userQuery, dur.String()),
true,
resultSlice,
}
if err := s.template.Execute(w, data); err != nil {
s.Logger.Print("Error executing template: ", err)
}
} else {
http.Error(w, "Unsupported method", http.StatusMethodNotAllowed)
}
}
// serveIndex serves the plain index for the GET request and POST failovers
func serveIndex(s *HTTPServer, w http.ResponseWriter, r *http.Request) error {
data := struct {
Title string
Headline string
ReturnResults bool
LogMessages []string
}{
"Ekanite query interface",
"Ekanite query interface",
false,
[]string{},
}
return s.template.Execute(w, data)
}
// dontCache sets necessary headers to avoid client and intermediate caching of response
func dontCache(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Expires", time.Unix(0, 0).Format(time.RFC1123))
w.Header().Set("Last-Modified", time.Now().Format(time.RFC1123))
w.Header().Set("Cache-Control", "private, no-store, max-age=0, no-cache, must-revalidate, post-check=0, pre-check=0")
return
}
const templateSource string = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>{{ $.Title }}</title>
<style type="text/css">
body, h2 {
margin: 50px;
font-family: sans-serif;
font-size: 13px;
}
h2 {
font-size: 15px;
}
.button {
background: #3498db;
background-image: linear-gradient(to bottom, #3498db, #2980b9);
border-radius: 4px;
font-family: sans-serif;
color: #ffffff;
font-size: 15px;
padding: 10px 20px 10px 20px;
margin-bottom: 20px;
text-decoration: none;
}
hr {
margin-bottom: 10px;
margin-top: 10px;
}
.button:hover {
background: #3cb0fd;
background-image: linear-gradient(to bottom, #3cb0fd, #3498db);
text-decoration: none;
}
textarea {
margin: 20px 20px 20px 0;
}
</style>
</head>
<body>
<h2>{{ $.Headline }}</h2>
<div id="help">Query language reference: <a href="http://godoc.org/github.com/blevesearch/bleve#NewQueryStringQuery">bleve</a></div>
<form action="/" method="POST">
<textarea name="query" cols="100" rows="2"></textarea>
<br>
<input name="submit" type="submit" class="button" value="Query">
</form>
{{ if $.ReturnResults }}
<hr>
<ul>
{{range $message := $.LogMessages }}
<li>{{ $message }}</li>
{{ end }}
</ul>
{{ end }}
</body>
</html>
`