Debian Codegraph @

cmd/present/play.go

raw symbols SCIP
1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package main
6
7 import (
8 "bytes"
9 "fmt"
10 "io/fs"
11 "net/http"
12 "net/url"
13 "time"
14
15 "golang.org/x/tools/playground/socket"
16 "golang.org/x/tools/present"
17
18 // This will register a handler at /compile that will proxy to the
19 // respective endpoints at play.golang.org. This allows the frontend to call
20 // these endpoints without needing cross-origin request sharing (CORS).
21 // Note that this is imported regardless of whether the endpoints are used or
22 // not (in the case of a local socket connection, they are not called).
23 _ "golang.org/x/tools/playground"
24 )
25
26 var scripts = []string{"jquery.js", "jquery-ui.js", "playground.js", "play.js"}
27
28 // playScript registers an HTTP handler at /play.js that serves all the
29 // scripts specified by the variable above, and appends a line that
30 // initializes the playground with the specified transport.
31 func playScript(fsys fs.FS, transport string) {
32 modTime := time.Now()
33 var buf bytes.Buffer
34 for _, p := range scripts {
35 b, err := fs.ReadFile(fsys, "static/"+p)
36 if err != nil {
37 panic(err)
38 }
39 buf.Write(b)
40 }
41 fmt.Fprintf(&buf, "\ninitPlayground(new %v());\n", transport)
42 b := buf.Bytes()
43 http.HandleFunc("/play.js", func(w http.ResponseWriter, r *http.Request) {
44 w.Header().Set("Content-type", "application/javascript")
45 http.ServeContent(w, r, "", modTime, bytes.NewReader(b))
46 })
47 }
48
49 func initPlayground(fsys fs.FS, origin *url.URL) {
50 if !present.PlayEnabled {
51 return
52 }
53 if *usePlayground {
54 playScript(fsys, "HTTPTransport")
55 return
56 }
57
58 playScript(fsys, "SocketTransport")
59 http.Handle("/socket", socket.NewHandler(origin))
60 }
61
62 func playable(c present.Code) bool {
63 play := present.PlayEnabled && c.Play
64
65 // Restrict playable files to only Go source files when using play.golang.org,
66 // since there is no method to execute shell scripts there.
67 if *usePlayground {
68 return play && c.Ext == ".go"
69 }
70 return play
71 }