forked from goadesign/plugins
/
mount_files.go
86 lines (79 loc) · 2.51 KB
/
mount_files.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
package goakit
import (
"fmt"
"path/filepath"
"strings"
"goa.design/goa/codegen"
"goa.design/goa/expr"
httpcodegen "goa.design/goa/http/codegen"
)
// MountFiles produces the files containing the HTTP handler mount functions
// that configure the mux to serve the requests.
func MountFiles(root *expr.RootExpr) []*codegen.File {
fw := make([]*codegen.File, len(root.API.HTTP.Services))
for i, svc := range root.API.HTTP.Services {
fw[i] = mountFile(svc)
}
return fw
}
// mountFile returns the file defining the mount handler functions for the given
// service.
func mountFile(svc *expr.HTTPServiceExpr) *codegen.File {
path := filepath.Join(codegen.Gendir, "http", codegen.SnakeCase(svc.Name()), "kitserver", "mount.go")
data := httpcodegen.HTTPServices.Get(svc.Name())
title := fmt.Sprintf("%s go-kit HTTP server encoders and decoders", svc.Name())
sections := []*codegen.SectionTemplate{
codegen.Header(title, "server", []*codegen.ImportSpec{
{Path: "net/http"},
{Path: "goa.design/goa/http", Name: "goahttp"},
}),
}
for _, e := range data.Endpoints {
sections = append(sections, &codegen.SectionTemplate{
Name: "goakit-mount-handler",
Source: mountHandlerT,
Data: e,
})
}
fm := codegen.TemplateFuncs()
fm["join"] = strings.Join
for _, fs := range data.FileServers {
sections = append(sections, &codegen.SectionTemplate{
Name: "goakit-mount-file-server",
Source: mountFileServerT,
Data: fs,
FuncMap: fm,
})
}
return &codegen.File{Path: path, SectionTemplates: sections}
}
// input: EndpointData
const mountHandlerT = `{{ printf "%s configures the mux to serve the %q service %q endpoint." .MountHandler .ServiceName .Method.Name | comment }}
func {{ .MountHandler }}(mux goahttp.Muxer, h http.Handler) {
f, ok := h.(http.HandlerFunc)
if !ok {
f = func(w http.ResponseWriter, r *http.Request) {
h.ServeHTTP(w, r)
}
}
{{- range .Routes }}
mux.Handle("{{ .Verb }}", "{{ .Path }}", f)
{{- end }}
}
`
// input: FileServerData
const mountFileServerT = `{{ printf "%s configures the mux to serve GET request made to %q." .MountHandler (join .RequestPaths ", ") | comment }}
func {{ .MountHandler }}(mux goahttp.Muxer) {
{{- if .IsDir }}
{{- range .RequestPaths }}
mux.Handle("GET", "{{ . }}", http.FileServer(http.Dir({{ printf "%q" $.FilePath }})))
{{- end }}
{{- else }}
{{- range .RequestPaths }}
mux.Handle("GET", "{{ . }}", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, {{ printf "%q" $.FilePath }})
}))
{{- end }}
{{- end }}
}
`