-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstory.go
117 lines (92 loc) · 2.08 KB
/
story.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package choosebook
import (
"encoding/json"
"html/template"
"io"
"log"
"net/http"
"strings"
)
var tpl *template.Template
var defaultHandlerTempl = `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Choose Your Own Adventure Book</title>
</head>
<body>
<h1>{{.Title}}</h1>
{{range .Paragraphs}}
<p>{{.}}</p>
{{end}}
<ul>
{{range .Options}}
<li><a href="/{{.Chapter}}">{{.Text}}</a> </li>
{{end}}
</ul>
</body>
</html>`
type Option struct {
Text string `json:"text"`
Chapter string `json:"arc"`
}
type Chapter struct {
Title string `json:"title"`
Paragraphs []string `json:"story"`
Options []Option `json:"options"`
}
type MyHandler struct {
story Story
template *template.Template
pathFunc func(r *http.Request) string
}
type HandlerOption func(r *MyHandler)
type Story map[string]Chapter
func JsonStory(r io.Reader) (Story, error) {
var story Story
d := json.NewDecoder(r)
if err := d.Decode(&story); err != nil {
return nil, err
}
return story, nil
}
func WithTemplate(t *template.Template) HandlerOption {
return func(h *MyHandler) {
h.template = t
}
}
func WithPathFunc(fn func(r *http.Request) string) HandlerOption {
return func(h *MyHandler) {
h.pathFunc = fn
}
}
func NewHandler(s Story, opts ...HandlerOption) MyHandler {
h := MyHandler{s, tpl, defaultPathFunc}
for _, opt := range opts {
opt(&h)
}
return h
}
func defaultPathFunc(r *http.Request) string {
path := strings.TrimSpace(r.URL.Path)
if path == "" || path == "/" {
path = "/intro"
}
return path[1:]
}
func (h MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
path := h.pathFunc(r)
if chapter, ok := h.story[path]; ok {
err := h.template.Execute(w, chapter)
if err != nil {
log.Printf("%v", err)
http.Error(w, "Something went wrong...", http.StatusInternalServerError)
}
return
}
http.Error(w, "Chapter not found...", http.StatusNotFound)
}
func init() {
tpl = template.Must(template.New("").Parse(defaultHandlerTempl))
}