-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
72 lines (58 loc) · 1.4 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
package main
import (
"fmt"
"log"
"net/http"
"os"
"github.com/g-harel/gothrough/internal/typeindex"
"github.com/g-harel/gothrough/pages"
)
func headerResponse(w http.ResponseWriter, statusCode int) {
w.WriteHeader(statusCode)
fmt.Fprintf(w, "%d %s", statusCode, http.StatusText(statusCode))
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
indexFilename := os.Getenv("INDEX")
if indexFilename == "" {
indexFilename = ".index"
}
fi, err := os.Stat(indexFilename)
if err != nil {
panic(fmt.Sprintf("stat index file: %v", err))
}
log.Printf("Index size: %v bytes", fi.Size())
f, err := os.Open(indexFilename)
if err != nil {
panic(fmt.Sprintf("open index file: %v", err))
}
idx, err := typeindex.NewIndexFromBytes(f)
if err != nil {
panic(err)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
pages.Home(idx.Packages())(w, r)
})
http.HandleFunc("/search", func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
headerResponse(w, http.StatusBadRequest)
return
}
query := r.Form.Get("q")
if query == "" {
headerResponse(w, http.StatusBadRequest)
return
}
results, err := idx.Search(query)
if err != nil {
panic(err)
}
pages.Results(query, results)(w, r)
})
log.Printf("accepting connections at :%v", port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%v", port), nil))
}