-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
139 lines (105 loc) · 2.47 KB
/
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
package main
import (
"encoding/json"
"fmt"
"go/build"
"log"
"net/http"
"path/filepath"
"sort"
"strings"
"time"
)
const importpath = "github.com/paulsamways/gopkgsearch"
func webdir() string {
pkg, err := build.Import(importpath, "", build.FindOnly)
if err != nil {
log.Printf("Couldn't determine web directory: %s", err)
return "./web"
}
return filepath.Join(pkg.Dir, "web")
}
func listen() {
http.Handle("/", http.FileServer(http.Dir(webdir())))
http.HandleFunc("/query", query)
err := http.ListenAndServe(*addr, nil)
if err != nil {
log.Fatalf("Couldn't listen for http requests on %s. %s", *addr, err)
}
}
func writeJson(w http.ResponseWriter, o interface{}) bool {
w.Header().Add("Content-Type", "application/json")
enc := json.NewEncoder(w)
if err := enc.Encode(o); err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "{'err': '%s'}", err)
return false
}
return true
}
// Matches two values, returning a score 0..1. 0 no match, 1 exact match.
func match(a, b string) float32 {
idx := strings.Index(a, b)
if idx == -1 {
return 0
}
la, lb := float32(len(a)), float32(len(b))
if idx == 0 && la == lb {
return 1
}
lenScore := 1.0 - ((la - lb) / la)
posScore := (la - float32(idx)) / la
return (lenScore + posScore) / 2.0
}
type score struct {
element *Element
score float32
}
type scores []score
func (s scores) Len() int { return len(s) }
func (s scores) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s scores) Less(i, j int) bool { return s[i].score > s[j].score }
func query(w http.ResponseWriter, req *http.Request) {
result := make(scores, 0)
start := time.Now()
queries := req.URL.Query()["q"]
obj := ""
pkg := ""
recv := ""
if len(queries) > 0 {
parts := strings.Split(queries[0], ".")
switch len(parts) {
case 1:
obj = strings.ToLower(parts[0])
case 2:
pkg = parts[0]
obj = strings.ToLower(parts[1])
case 3:
pkg = parts[0]
recv = strings.ToLower(parts[1])
obj = strings.ToLower(parts[2])
}
}
for _, e := range elements {
if len(pkg) > 0 && e.Package != pkg {
continue
}
if len(recv) > 0 && e.recv != recv && e.name != recv {
continue
}
if m := match(e.name, obj); m > 0 {
result = append(result, score{e, m})
}
}
sort.Sort(result)
c := len(result)
if c > 50 {
c = 50
}
r := make([]*Element, c)
for i, v := range result[:c] {
r[i] = v.element
}
fmt.Printf("Found %d results in %s.\n", c, time.Since(start))
writeJson(w, r)
}