1 // Copyright 2010 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.
14 "golang.org/x/tools/godoc"
15 "golang.org/x/tools/godoc/redirect"
16 "golang.org/x/tools/godoc/vfs"
19 // This package registers "/compile" and "/share" handlers
20 // that redirect to the golang.org playground.
21 import _ "golang.org/x/tools/playground"
24 pres *godoc.Presentation
28 func registerHandlers(pres *godoc.Presentation) {
30 panic("nil Presentation")
32 mux := http.NewServeMux()
33 mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
34 if req.URL.Path == "/" {
35 http.Redirect(w, req, "/pkg/", http.StatusFound)
38 pres.ServeHTTP(w, req)
40 mux.Handle("/pkg/C/", redirect.Handler("/cmd/cgo/"))
41 mux.HandleFunc("/fmt", fmtHandler)
42 redirect.Register(mux)
47 func readTemplate(name string) *template.Template {
49 panic("no global Presentation set yet")
51 path := "lib/godoc/" + name
53 // use underlying file system fs to read the template file
54 // (cannot use template ParseFile functions directly)
55 data, err := vfs.ReadFile(fs, path)
57 log.Fatal("readTemplate: ", err)
59 // be explicit with errors (for app engine use)
60 t, err := template.New(name).Funcs(pres.FuncMap()).Parse(string(data))
62 log.Fatal("readTemplate: ", err)
67 func readTemplates(p *godoc.Presentation) {
68 p.CallGraphHTML = readTemplate("callgraph.html")
69 p.DirlistHTML = readTemplate("dirlist.html")
70 p.ErrorHTML = readTemplate("error.html")
71 p.ExampleHTML = readTemplate("example.html")
72 p.GodocHTML = readTemplate("godoc.html")
73 p.ImplementsHTML = readTemplate("implements.html")
74 p.MethodSetHTML = readTemplate("methodset.html")
75 p.PackageHTML = readTemplate("package.html")
76 p.PackageRootHTML = readTemplate("packageroot.html")
77 p.SearchHTML = readTemplate("search.html")
78 p.SearchDocHTML = readTemplate("searchdoc.html")
79 p.SearchCodeHTML = readTemplate("searchcode.html")
80 p.SearchTxtHTML = readTemplate("searchtxt.html")
83 type fmtResponse struct {
88 // fmtHandler takes a Go program in its "body" form value, formats it with
89 // standard gofmt formatting, and writes a fmtResponse as a JSON object.
90 func fmtHandler(w http.ResponseWriter, r *http.Request) {
91 resp := new(fmtResponse)
92 body, err := format.Source([]byte(r.FormValue("body")))
94 resp.Error = err.Error()
96 resp.Body = string(body)
98 w.Header().Set("Content-type", "application/json; charset=utf-8")
99 json.NewEncoder(w).Encode(resp)