-
Notifications
You must be signed in to change notification settings - Fork 4
/
web.go
172 lines (154 loc) · 3.98 KB
/
web.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
package main
import (
"bytes"
"crypto/md5"
"encoding/json"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path"
"code.google.com/p/go.net/websocket"
"github.com/nogiushi/marvin/nog"
"github.com/nogiushi/marvin/persist"
)
var pkg struct {
Version string `json:"version"`
}
var site *template.Template
var templates = make(map[string]*template.Template)
func ReadVersion() {
if j, err := os.OpenFile(path.Join(*Root, "bower.json"), os.O_RDONLY, 0666); err == nil {
dec := json.NewDecoder(j)
if err = dec.Decode(&pkg); err != nil {
log.Println("WARNING: could not decode bower.json", err)
}
j.Close()
} else {
log.Println("WARNING: could not open bower.json", err)
}
}
type longExpireHandler struct {
h http.Handler
}
func longExpire(h http.Handler) http.Handler {
return &longExpireHandler{h}
}
func (le *longExpireHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ttl := int64(365 * 86400)
w.Header().Set("Cache-Control", fmt.Sprintf("max-age=%d", ttl))
le.h.ServeHTTP(w, r)
}
func getTemplate(name string) *template.Template {
if t, ok := templates[name]; ok {
return t
} else {
if site == nil {
site = template.Must(template.ParseFiles(path.Join(*Root, "templates/site.html")))
}
t, err := site.Clone()
if err != nil {
log.Fatal("cloning site: ", err)
}
t = template.Must(t.ParseFiles(path.Join(*Root, name)))
templates[name] = t
return t
}
}
type templateData map[string]interface{}
func writeTemplate(t *template.Template, d templateData, w http.ResponseWriter) {
var bw bytes.Buffer
h := md5.New()
mw := io.MultiWriter(&bw, h)
err := t.ExecuteTemplate(mw, "html", d)
if err == nil {
w.Header().Set("ETag", fmt.Sprintf(`"%x"`, h.Sum(nil)))
w.Header().Set("Content-Length", fmt.Sprintf("%d", bw.Len()))
w.Write(bw.Bytes())
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func handleTemplate(prefix, name string, data templateData) {
t := getTemplate("templates/" + name + ".html")
http.HandleFunc(prefix, func(w http.ResponseWriter, req *http.Request) {
d := templateData{}
d["Title"] = name
d["Version"] = pkg.Version
if data != nil {
for k, v := range data {
d[k] = v
}
}
if req.URL.Path == prefix {
d["Found"] = true
} else {
w.Header().Set("Cache-Control", "max-age=10, must-revalidate")
w.WriteHeader(http.StatusNotFound)
}
writeTemplate(t, d, w)
})
}
func AddHandlers(n *nog.Nog) {
handleTemplate("/", "home", templateData{"Marvin": n})
fs := longExpire(http.FileServer(http.Dir(path.Join(*Root, "static/"))))
http.Handle("/"+pkg.Version+"/", fs)
http.Handle("/message", websocket.Handler(func(ws *websocket.Conn) {
req := ws.Request()
name := fmt.Sprintf("web-%s", req.RemoteAddr)
// who := req.RemoteAddr
// if req.TLS != nil {
// for _, c := range req.TLS.PeerCertificates {
// who = c.Subject.CommonName
// }
// }
n.Register(name, func(in <-chan nog.Message, out chan<- nog.Message) {
go func() {
for {
var m nog.Message
if err := websocket.JSON.Receive(ws, &m); err == nil {
//m.Who = who
out <- m
} else {
log.Println("Message Websocket receive err:", err)
return
}
}
}()
for m := range in {
if err := websocket.JSON.Send(ws, &m); err != nil {
log.Println("Message Websocket send err:", err)
break
}
}
out <- nog.Message{What: "stopped"}
close(out)
})
n.Start(name)
n.Unregister(name)
ws.Close()
}))
}
func AddPersistenceHandlers(p *persist.Persist) {
http.HandleFunc("/messages", func(w http.ResponseWriter, req *http.Request) {
if req.Method == "GET" {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := req.ParseForm(); err == nil {
_, ok := req.Form["since"]
if true || ok {
log := p.Log()
ec := json.NewEncoder(w)
if err := ec.Encode(log); err != nil {
return
}
}
} else {
log.Println("Error parsing form:", err)
}
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
}
})
}