forked from golang/gddo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
245 lines (214 loc) · 5.88 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
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
// Copyright 2013 The Go Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd.
// Package talksapp implements the go-talks.appspot.com server.
package talksapp
import (
"bytes"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"os"
"path"
"time"
"appengine"
"appengine/memcache"
"appengine/urlfetch"
"github.com/golang/gddo/gosrc"
"github.com/golang/gddo/httputil"
"golang.org/x/tools/present"
)
var (
presentTemplates = map[string]*template.Template{
".article": parsePresentTemplate("article.tmpl"),
".slide": parsePresentTemplate("slides.tmpl"),
}
homeArticle = loadHomeArticle()
contactEmail = "golang-dev@googlegroups.com"
// used for mocking in tests
getPresentation = gosrc.GetPresentation
playCompileURL = "http://play.golang.org/compile"
)
func init() {
http.Handle("/", handlerFunc(serveRoot))
http.Handle("/compile", handlerFunc(serveCompile))
http.Handle("/bot.html", handlerFunc(serveBot))
present.PlayEnabled = true
if s := os.Getenv("CONTACT_EMAIL"); s != "" {
contactEmail = s
}
}
func playable(c present.Code) bool {
return present.PlayEnabled && c.Play && c.Ext == ".go"
}
func parsePresentTemplate(name string) *template.Template {
t := present.Template()
t = t.Funcs(template.FuncMap{"playable": playable})
if _, err := t.ParseFiles("present/templates/"+name, "present/templates/action.tmpl"); err != nil {
panic(err)
}
t = t.Lookup("root")
if t == nil {
panic("root template not found for " + name)
}
return t
}
func loadHomeArticle() []byte {
const fname = "assets/home.article"
f, err := os.Open(fname)
if err != nil {
panic(err)
}
defer f.Close()
doc, err := present.Parse(f, fname, 0)
if err != nil {
panic(err)
}
var buf bytes.Buffer
if err := renderPresentation(&buf, fname, doc); err != nil {
panic(err)
}
return buf.Bytes()
}
func renderPresentation(w io.Writer, fname string, doc *present.Doc) error {
t := presentTemplates[path.Ext(fname)]
if t == nil {
return errors.New("unknown template extension")
}
data := struct {
*present.Doc
Template *template.Template
PlayEnabled bool
}{
doc,
t,
true,
}
return t.Execute(w, &data)
}
type presFileNotFoundError string
func (s presFileNotFoundError) Error() string { return fmt.Sprintf("File %s not found.", string(s)) }
func writeHTMLHeader(w http.ResponseWriter, status int) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
}
func writeTextHeader(w http.ResponseWriter, status int) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(status)
}
func httpClient(r *http.Request) *http.Client {
c := appengine.NewContext(r)
github := httputil.NewAuthTransportFromEnvironment(nil)
return &http.Client{
Transport: &httputil.AuthTransport{
Token: github.Token,
ClientID: github.ClientID,
ClientSecret: github.ClientSecret,
Base: &urlfetch.Transport{Context: c, Deadline: 10 * time.Second},
UserAgent: fmt.Sprintf("%s (+http://%s/-/bot)", appengine.AppID(c), r.Host),
},
}
}
type handlerFunc func(http.ResponseWriter, *http.Request) error
func (f handlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
err := f(w, r)
if err == nil {
return
} else if gosrc.IsNotFound(err) {
writeTextHeader(w, 400)
io.WriteString(w, "Not Found.")
} else if e, ok := err.(*gosrc.RemoteError); ok {
writeTextHeader(w, 500)
fmt.Fprintf(w, "Error accessing %s.\n%v", e.Host, e)
c.Infof("Remote error %s: %v", e.Host, e)
} else if e, ok := err.(presFileNotFoundError); ok {
writeTextHeader(w, 200)
io.WriteString(w, e.Error())
} else if err != nil {
writeTextHeader(w, 500)
io.WriteString(w, "Internal server error.")
c.Errorf("Internal error %v", err)
}
}
func serveRoot(w http.ResponseWriter, r *http.Request) error {
switch {
case r.Method != "GET" && r.Method != "HEAD":
writeTextHeader(w, 405)
_, err := io.WriteString(w, "Method not supported.")
return err
case r.URL.Path == "/":
writeHTMLHeader(w, 200)
_, err := w.Write(homeArticle)
return err
default:
return servePresentation(w, r)
}
}
func servePresentation(w http.ResponseWriter, r *http.Request) error {
c := appengine.NewContext(r)
importPath := r.URL.Path[1:]
item, err := memcache.Get(c, importPath)
if err == nil {
writeHTMLHeader(w, 200)
w.Write(item.Value)
return nil
} else if err != memcache.ErrCacheMiss {
return err
}
c.Infof("Fetching presentation %s.", importPath)
pres, err := getPresentation(httpClient(r), importPath)
if err != nil {
return err
}
ctx := &present.Context{
ReadFile: func(name string) ([]byte, error) {
if p, ok := pres.Files[name]; ok {
return p, nil
}
return nil, presFileNotFoundError(name)
},
}
doc, err := ctx.Parse(bytes.NewReader(pres.Files[pres.Filename]), pres.Filename, 0)
if err != nil {
return err
}
var buf bytes.Buffer
if err := renderPresentation(&buf, importPath, doc); err != nil {
return err
}
if err := memcache.Add(c, &memcache.Item{
Key: importPath,
Value: buf.Bytes(),
Expiration: time.Hour,
}); err != nil {
return err
}
writeHTMLHeader(w, 200)
_, err = w.Write(buf.Bytes())
return err
}
func serveCompile(w http.ResponseWriter, r *http.Request) error {
client := urlfetch.Client(appengine.NewContext(r))
if err := r.ParseForm(); err != nil {
return err
}
resp, err := client.PostForm(playCompileURL, r.Form)
if err != nil {
return err
}
defer resp.Body.Close()
w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
_, err = io.Copy(w, resp.Body)
return err
}
func serveBot(w http.ResponseWriter, r *http.Request) error {
c := appengine.NewContext(r)
writeTextHeader(w, 200)
_, err := fmt.Fprintf(w, "Contact %s for help with the %s bot.", contactEmail, appengine.AppID(c))
return err
}