-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathhandler.go
65 lines (55 loc) · 1.33 KB
/
handler.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
package boltd
import (
"net/http"
"strconv"
"strings"
"github.com/boltdb/bolt"
"github.com/boltdb/boltd/templates"
)
// NewHandler returns a new root HTTP handler.
func NewHandler(db *bolt.DB) http.Handler {
h := &handler{db}
mux := http.NewServeMux()
mux.HandleFunc("/", h.index)
mux.HandleFunc("/page", h.page)
return mux
}
type handler struct {
db *bolt.DB
}
func (h *handler) index(w http.ResponseWriter, r *http.Request) {
templates.Index(w)
}
func (h *handler) page(w http.ResponseWriter, r *http.Request) {
err := h.db.View(func(tx *bolt.Tx) error {
showUsage := (r.FormValue("usage") == "true")
// Use the direct page id, if available.
if r.FormValue("id") != "" {
id, _ := strconv.Atoi(r.FormValue("id"))
return templates.Page(w, r, tx, nil, id, showUsage)
}
// Otherwise extract the indexes and traverse.
indexes, err := indexes(r)
if err != nil {
return err
}
return templates.Page(w, r, tx, indexes, 0, showUsage)
})
if err != nil {
templates.Error(w, err)
}
}
// parses and returns all indexes from a request.
func indexes(r *http.Request) ([]int, error) {
var a = []int{0}
if len(r.FormValue("index")) > 0 {
for _, s := range strings.Split(r.FormValue("index"), ":") {
i, err := strconv.Atoi(s)
if err != nil {
return nil, err
}
a = append(a, i)
}
}
return a, nil
}