-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
96 lines (79 loc) · 1.92 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package main
import (
"database/sql"
"encoding/json"
"fmt"
"html/template"
"log"
"net/http"
"os"
"time"
_ "modernc.org/sqlite"
)
func main() {
logger := log.New(os.Stderr, "", log.Lshortfile)
server, err := NewServer(logger, "templates/*.html", "words.sqlite")
if err != nil {
logger.Fatalf("failed to create server: %v", err)
}
err = http.ListenAndServe(":"+os.Getenv("PORT"), server)
if err != nil {
logger.Fatalf("failed to start server: %v", err)
}
}
type Log interface {
Printf(msg string, args ...interface{})
Println(args ...interface{})
}
type Server struct {
log Log
views *template.Template
db *sql.DB
}
func NewServer(logger Log, templatesPath, dbName string) (*Server, error) {
db, err := sql.Open("sqlite", dbName)
if err != nil {
return nil, err
}
views, err := template.ParseGlob(templatesPath)
if err != nil {
return nil, fmt.Errorf("failed to load templates from %q: %w", templatesPath, err)
}
return &Server{
db: db,
log: logger,
views: views,
}, nil
}
func (server *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query().Get("q")
if query == "" {
server.views.ExecuteTemplate(w, "index.html", nil)
return
}
start := time.Now()
rows, err := server.db.Query("SELECT word FROM wordsfts where \"word\" MATCH ?", query+"*")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
var results []string
var word string
for rows.Next() {
err = rows.Scan(&word)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
results = append(results, word)
}
rows.Close()
duration := time.Since(start)
server.log.Printf("Performed query %q in %v", query, duration)
server.writeJSON(w, results)
}
func (server *Server) writeJSON(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
_ = enc.Encode(data)
}