-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb_server.go
More file actions
69 lines (59 loc) · 1.51 KB
/
web_server.go
File metadata and controls
69 lines (59 loc) · 1.51 KB
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
package main
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
"os"
"slices"
"time"
)
type WebSearchHandler struct{}
type WebSearchData struct {
Provider string
Query string
Results []SearchResult
FetchTime float64
}
func (h WebSearchHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
queryParams := r.URL.Query()
query := queryParams.Get("q")
if query == "" {
w.WriteHeader(400)
w.Write([]byte("Missing query parameter 'q'"))
return
}
provider := queryParams.Get("provider")
if provider == "" {
provider = config.DefaultProvider
}
if !slices.Contains(config.EnabledProviders, provider) {
w.WriteHeader(400)
w.Write([]byte("Invalid search provider"))
}
format := queryParams.Get("format")
startTime := time.Now()
results := runQuery(query, provider)
if format == "json" {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(results)
return
}
cwd, _ := os.Getwd()
w.Header().Set("Content-Type", "text/html; charset=utf-8")
t, _ := template.ParseFiles(fmt.Sprintf("%s/templates/results.html", cwd))
t.Execute(w, WebSearchData{
Provider: provider,
Query: query,
Results: results,
FetchTime: time.Since(startTime).Seconds(),
})
}
func setupWebServer(mux *http.ServeMux) {
mux.Handle("/search", WebSearchHandler{})
cwd, _ := os.Getwd()
static := http.FileServer(http.Dir(fmt.Sprintf("%s/static", cwd)))
mux.Handle("/", static)
mux.Handle("/favicon.ico", static)
mux.Handle("/static/", http.StripPrefix("/static/", static))
}