-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
82 lines (72 loc) · 1.73 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
package main
import (
"bytes"
"encoding/json"
"fmt"
"index/suffixarray"
"io/ioutil"
"log"
"net/http"
"os"
)
func main() {
searcher := Searcher{}
err := searcher.Load("completeworks.txt")
if err != nil {
log.Fatal(err)
}
fs := http.FileServer(http.Dir("./static"))
http.Handle("/", fs)
http.HandleFunc("/search", handleSearch(searcher))
port := os.Getenv("PORT")
if port == "" {
port = "3001"
}
fmt.Printf("shakesearch available at http://localhost:%s...", port)
err = http.ListenAndServe(fmt.Sprintf(":%s", port), nil)
if err != nil {
log.Fatal(err)
}
}
type Searcher struct {
CompleteWorks string
SuffixArray *suffixarray.Index
}
func handleSearch(searcher Searcher) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
query, ok := r.URL.Query()["q"]
if !ok || len(query[0]) < 1 {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("missing search query in URL params"))
return
}
results := searcher.Search(query[0])
buf := &bytes.Buffer{}
enc := json.NewEncoder(buf)
err := enc.Encode(results)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("encoding failure"))
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(buf.Bytes())
}
}
func (s *Searcher) Load(filename string) error {
dat, err := ioutil.ReadFile(filename)
if err != nil {
return fmt.Errorf("Load: %w", err)
}
s.CompleteWorks = string(dat)
s.SuffixArray = suffixarray.New(dat)
return nil
}
func (s *Searcher) Search(query string) []string {
idxs := s.SuffixArray.Lookup([]byte(query), -1)
results := []string{}
for _, idx := range idxs {
results = append(results, s.CompleteWorks[idx-250:idx+250])
}
return results
}