-
Notifications
You must be signed in to change notification settings - Fork 0
/
web_server.go
79 lines (67 loc) · 1.71 KB
/
web_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
79
package main
import (
"log"
"net/http"
"regexp"
"text/template"
)
var validPath = regexp.MustCompile("^/|(index|search)|/([a-zA-Z0-9]+)$")
var templates = template.Must(template.ParseFiles(
"template/index.html",
"template/search.html"))
type inputPage struct {
RepoName []byte
languageName []byte
}
// Page structure handle variables sent to client
type Page struct {
Body []byte
}
func executeSearch(repoName, languageName string) *map[string]languageStats {
var params string
if repoName != "" {
params = "q=in:name+" + repoName + "+"
}
if languageName != "" {
if params == "" {
params = "q=language:" + languageName
} else {
params += "language:" + languageName
}
}
repoStats, err := getAggregatedRepo(params)
if err != nil {
log.Print(err)
}
return &repoStats
}
func makeHandler(httpFunction func(http.ResponseWriter, *http.Request)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
m := validPath.FindStringSubmatch(r.URL.Path)
if m == nil {
http.NotFound(w, r)
return
}
httpFunction(w, r)
}
}
func renderTemplate(w http.ResponseWriter, template string, p interface{}) {
err := templates.ExecuteTemplate(w, template+".html", p)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
p := &Page{}
renderTemplate(w, "index", p)
}
func searchHandler(w http.ResponseWriter, r *http.Request) {
repoName := r.FormValue("repoName")
languageName := r.FormValue("languageName")
repo := executeSearch(repoName, languageName)
renderTemplate(w, "search", repo)
}
func errorHandler(w http.ResponseWriter, r *http.Request) {
p := &Page{}
renderTemplate(w, "error", p)
}