/
synthesizer.go
93 lines (82 loc) · 1.83 KB
/
synthesizer.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
// Copyright 2011 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"text/template"
)
// MakeMain creates the synthetic main package for a Go App Engine app.
func MakeMain(app *App) (string, error) {
buf := new(bytes.Buffer)
if err := mainTemplate.Execute(buf, app); err != nil {
return "", err
}
return buf.String(), nil
}
// MakeExtraImports creates the synthetic extra-imports file for a single package.
func MakeExtraImports(packageName string, extraImports []string) (string, error) {
buf := new(bytes.Buffer)
err := extraImportsTemplate.Execute(buf, struct {
PackageName string
ExtraImports []string
}{
packageName,
extraImports,
})
if err != nil {
return "", err
}
return buf.String(), nil
}
var mainTemplate = template.Must(template.New("main").Parse(
`package main
import (
{{with .InternalPkg}}
internal {{printf "%q" .}}
{{else}}
"io"
"log"
"net/http"
"net/url"
{{end}}
// Top-level app packages
{{range .RootPackages}}
_ "{{.ImportPath}}"
{{end}}
)
func main() {
{{if .InternalPkg}}
internal.Main()
{{else}}
installHealthChecker()
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatalf("http.ListenAndServe: %v", err)
}
{{end}}
}
{{if not .InternalPkg}}
func installHealthChecker() {
const healthPath = "/_ah/health"
hreq := &http.Request{
Method: "GET",
URL: &url.URL{
Path: healthPath,
},
}
if _, pat := http.DefaultServeMux.Handler(hreq); pat != healthPath {
http.HandleFunc(healthPath, func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "ok")
})
}
}
{{end}}
`))
var extraImportsTemplate = template.Must(template.New("extraImports").Parse(
`package {{.PackageName}}
import (
{{range .ExtraImports}}
_ "{{.}}"
{{end}}
)
`))