forked from pedronasser/caddy-search
/
search.go
92 lines (75 loc) · 2 KB
/
search.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
package search
import (
"encoding/json"
"net/http"
"time"
"github.com/mholt/caddy/middleware"
"github.com/pedronasser/caddy-search/indexer"
)
// Handler creates a new handler for the search middleware
func Handler(next middleware.Handler, config *Config, index indexer.Handler, pipeline *Pipeline) middleware.Handler {
return &Search{next, config, index, pipeline}
}
// Search represents this middleware structure
type Search struct {
Next middleware.Handler
*Config
Indexer indexer.Handler
*Pipeline
}
// ServerHTTP is the HTTP handler for this middleware
func (s *Search) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
if middleware.Path(r.URL.Path).Matches(s.Config.Endpoint) {
if r.Header.Get("Accept") == "application/json" {
return s.SearchJSON(w, r)
}
return s.SearchJSON(w, r)
}
record := s.Indexer.Record(r.URL.String())
go s.Pipeline.Pipe(record)
return s.Next.ServeHTTP(&searchResponseWriter{w, record}, r)
}
// Result is the structure for the search result
type Result struct {
Path string
Title string
Body string
Modified time.Time
}
// SearchJSON ...
func (s *Search) SearchJSON(w http.ResponseWriter, r *http.Request) (status int, err error) {
var jresp []byte
q := r.URL.Query().Get("q")
indexResult := s.Indexer.Search(q)
results := make([]Result, len(indexResult))
for i, result := range indexResult {
body := result.Body()
results[i] = Result{
Path: result.Path(),
Title: result.Title(),
Modified: result.Modified(),
Body: string(body),
}
}
jresp, err = json.Marshal(results)
if err != nil {
return 500, err
}
w.Write(jresp)
return 200, err
}
type searchResponseWriter struct {
w http.ResponseWriter
record indexer.Record
}
func (r *searchResponseWriter) Header() http.Header {
return r.w.Header()
}
func (r *searchResponseWriter) WriteHeader(code int) {
r.w.WriteHeader(code)
}
func (r *searchResponseWriter) Write(p []byte) (int, error) {
defer r.record.Write(p)
n, err := r.w.Write(p)
return n, err
}