-
Notifications
You must be signed in to change notification settings - Fork 0
/
boggleweb.go
50 lines (39 loc) · 1.13 KB
/
boggleweb.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
package boggleweb
import (
"net/http"
"html/template"
"encoding/json"
"os"
"bufio"
"log"
"boggle"
)
var indexTemplate = template.Must(template.ParseFiles("base.html", "index.html"))
var boggleDictionary *boggle.BoggleDictionary
func init() {
http.HandleFunc("/api/boggle/words", solve)
http.HandleFunc("/", home)
dictFile, err := os.Open("dict.txt")
if err != nil {
panic(err)
}
defer dictFile.Close()
reader := bufio.NewReader(dictFile)
boggleDictionary = boggle.NewBoggleDictionaryFromReader(reader)
}
func home(w http.ResponseWriter, r *http.Request) {
if err := indexTemplate.Execute(w, nil); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func solve(w http.ResponseWriter, r *http.Request) {
board := boggle.NewBoardFromString(r.FormValue(""))
log.Printf("Dict: %q", boggleDictionary)
words := board.ScanAll(boggleDictionary)
if result, err := json.Marshal(words); err == nil {
w.Header().Set("Content-Type", "application/json")
w.Write(result)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}