This repository has been archived by the owner on Apr 23, 2023. It is now read-only.
forked from golang/playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit.go
95 lines (82 loc) · 2.33 KB
/
edit.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
// Copyright 2011 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.
package main
import (
"fmt"
"html/template"
"net/http"
"runtime"
"strings"
"cloud.google.com/go/datastore"
)
const hostname = "play.golang.org"
var editTemplate = template.Must(template.ParseFiles("edit.html"))
type editData struct {
Snippet *snippet
Share bool
Analytics bool
GoVersion string
}
func (s *server) handleEdit(w http.ResponseWriter, r *http.Request) {
// Redirect foo.play.golang.org to play.golang.org.
if strings.HasSuffix(r.Host, "."+hostname) {
http.Redirect(w, r, "https://"+hostname, http.StatusFound)
return
}
// Serve 404 for /foo.
if r.URL.Path != "/" && !strings.HasPrefix(r.URL.Path, "/p/") {
http.NotFound(w, r)
return
}
snip := &snippet{Body: []byte(hello)}
if strings.HasPrefix(r.URL.Path, "/p/") {
if !allowShare(r) {
w.WriteHeader(http.StatusUnavailableForLegalReasons)
w.Write([]byte(`<h1>Unavailable For Legal Reasons</h1><p>Viewing and/or sharing code snippets is not available in your country for legal reasons. This message might also appear if your country is misdetected. If you believe this is an error, please <a href="https://golang.org/issue">file an issue</a>.</p>`))
return
}
id := r.URL.Path[3:]
serveText := false
if strings.HasSuffix(id, ".go") {
id = id[:len(id)-3]
serveText = true
}
if err := s.db.GetSnippet(r.Context(), id, snip); err != nil {
if err != datastore.ErrNoSuchEntity {
s.log.Errorf("loading Snippet: %v", err)
}
http.Error(w, "Snippet not found", http.StatusNotFound)
return
}
if serveText {
if r.FormValue("download") == "true" {
w.Header().Set(
"Content-Disposition", fmt.Sprintf(`attachment; filename="%s.go"`, id),
)
}
w.Header().Set("Content-type", "text/plain; charset=utf-8")
w.Write(snip.Body)
return
}
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
data := &editData{
Snippet: snip,
Share: allowShare(r),
Analytics: r.Host == hostname,
GoVersion: runtime.Version(),
}
if err := editTemplate.Execute(w, data); err != nil {
s.log.Errorf("editTemplate.Execute(w, %+v): %v", data, err)
return
}
}
const hello = `package main
import (
"fmt"
)
func main() {
fmt.Println("Hello, playground")
}
`