-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
78 lines (65 loc) · 1.71 KB
/
server.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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
)
func searchHandlerFactory(docs Documents) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/search" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
if r.Method != "GET" {
http.Error(w, "Method is not supported.", http.StatusNotFound)
return
}
queries := r.URL.Query()
query := queries["query"][0]
if query == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
type ResultPair struct {
Path string `json:"path,omitempty"`
Freq float32 `json:"freq,omitempty"`
}
var result []ResultPair
for _, doc := range docs {
rank := float32(0)
lexer := NewLexer(query)
for {
token, err := lexer.NextToken()
if err != nil {
break
}
rank += doc.TermFrequency(token) * docs.InverseDocumentFrequency(token)
}
if rank > 0 {
result = append(result, ResultPair{Path: doc.Path, Freq: rank})
}
}
w.Header().Set("Content-Type", "application/json")
body, err := json.Marshal(map[string]interface{}{"length": len(result), "results": result})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
_, err = w.Write(body)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: could not write response body: %s\n", err)
w.WriteHeader(http.StatusInternalServerError)
}
}
}
func startServe(docs Documents) {
fileServer := http.FileServer(http.Dir("./static"))
http.Handle("/", fileServer)
http.HandleFunc("/search", searchHandlerFactory(docs))
fmt.Printf("Starting server at port 6969\n")
if err := http.ListenAndServe(":6969", nil); err != nil {
log.Fatal(err)
}
}