-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdocHandler.go
66 lines (51 loc) · 1.19 KB
/
docHandler.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
package searchpage
import (
"bytes"
"encoding/json"
"fmt"
"html"
"net/http"
bhttp "github.com/blevesearch/bleve/v2/http"
)
// jsonBuffer will buffer if content type is json, so we can apply formatting.
type jsonBuffer struct {
http.ResponseWriter
buf bytes.Buffer
}
func (m *jsonBuffer) isJSON() bool {
return m.Header().Get("Content-Type") == "application/json"
}
func (m *jsonBuffer) Write(b []byte) (int, error) {
if m.isJSON() {
return m.buf.Write(b)
}
return m.ResponseWriter.Write(b)
}
func (m *jsonBuffer) pretty() string {
if m.buf.Len() == 0 {
return ""
}
var out bytes.Buffer
json.Indent(&out, m.buf.Bytes(), "", " ")
return out.String()
}
var bleveDocHandler = bhttp.DocGetHandler{
IndexNameLookup: func(r *http.Request) string {
return r.URL.Query().Get("index")
},
DocIDLookup: func(r *http.Request) string {
return r.URL.Query().Get("doc")
},
}
func docHandler(w http.ResponseWriter, r *http.Request) {
buf := &jsonBuffer{w, bytes.Buffer{}}
bleveDocHandler.ServeHTTP(buf, r)
if !buf.isJSON() {
return
}
if r.Header.Get("Hx-Request") == "true" {
fmt.Fprintf(w, "<pre>%s</pre>", html.EscapeString(buf.pretty()))
return
}
w.Write([]byte(buf.pretty()))
}