forked from webrpc/gen-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go.tmpl
158 lines (136 loc) · 4.09 KB
/
server.go.tmpl
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
{{define "server"}}
{{- $typeMap := .TypeMap -}}
{{- if .Services }}
//
// Server
//
type WebRPCServer interface {
http.Handler
}
{{- range .Services}}
{{- $name := .Name -}}
{{ $serviceName := (printf "%sServer" (.Name | firstLetterToLower)) }}
type {{$serviceName}} struct {
{{.Name}}
}
func New{{ .Name | firstLetterToUpper }}Server(svc {{.Name}}) WebRPCServer {
return &{{$serviceName}}{
{{.Name}}: svc,
}
}
func (s *{{$serviceName}}) ServeHTTP(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = context.WithValue(ctx, HTTPResponseWriterCtxKey, w)
ctx = context.WithValue(ctx, HTTPRequestCtxKey, r)
ctx = context.WithValue(ctx, ServiceNameCtxKey, "{{.Name}}")
if r.Method != "POST" {
err := Errorf(ErrBadRoute, "unsupported method %q (only POST is allowed)", r.Method)
RespondWithError(w, err)
return
}
switch r.URL.Path {
{{- range .Methods}}
case "/rpc/{{$name}}/{{.Name}}":
s.serve{{.Name | firstLetterToUpper}}(ctx, w, r)
return
{{- end}}
default:
err := Errorf(ErrBadRoute, "no handler for path %q", r.URL.Path)
RespondWithError(w, err)
return
}
}
{{range .Methods }}
func (s *{{$serviceName}}) serve{{.Name | firstLetterToUpper}}(ctx context.Context, w http.ResponseWriter, r *http.Request) {
header := r.Header.Get("Content-Type")
i := strings.Index(header, ";")
if i == -1 {
i = len(header)
}
switch strings.TrimSpace(strings.ToLower(header[:i])) {
case "application/json":
s.serve{{ .Name | firstLetterToUpper }}JSON(ctx, w, r)
default:
err := Errorf(ErrBadRoute, "unexpected Content-Type: %q", r.Header.Get("Content-Type"))
RespondWithError(w, err)
}
}
func (s *{{$serviceName}}) serve{{ .Name | firstLetterToUpper }}JSON(ctx context.Context, w http.ResponseWriter, r *http.Request) {
var err error
ctx = context.WithValue(ctx, MethodNameCtxKey, "{{.Name}}")
{{- if .Inputs|len}}
reqContent := struct {
{{- range $i, $input := .Inputs}}
Arg{{$i}} {{template "type" dict "Type" $input.Type "Optional" $input.Optional "TypeMap" $typeMap}} `json:"{{firstLetterToLower $input.Name}}"`
{{- end}}
}{}
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil {
err = WrapError(ErrInternal, err, "failed to read request data")
RespondWithError(w, err)
return
}
defer r.Body.Close()
err = json.Unmarshal(reqBody, &reqContent)
if err != nil {
err = WrapError(ErrInvalidArgument, err, "failed to unmarshal request data")
RespondWithError(w, err)
return
}
{{- end}}
// Call service method
{{- range $i, $output := .Outputs}}
var ret{{$i}} {{template "type" dict "Type" $output.Type "Optional" $output.Optional "TypeMap" $typeMap}}
{{- end}}
func() {
defer func() {
// In case of a panic, serve a 500 error and then panic.
if rr := recover(); rr != nil {
RespondWithError(w, ErrorInternal("internal service panic"))
panic(rr)
}
}()
{{range $i, $output := .Outputs}}ret{{$i}}, {{end}}err = s.{{$name}}.{{.Name}}(ctx{{range $i, $_ := .Inputs}}, reqContent.Arg{{$i}}{{end}})
}()
{{- if .Outputs | len}}
respContent := struct {
{{- range $i, $output := .Outputs}}
Ret{{$i}} {{template "type" dict "Type" $output.Type "Optional" $output.Optional "TypeMap" $typeMap}} `json:"{{firstLetterToLower $output.Name}}"`
{{- end}}
}{ {{- range $i, $_ := .Outputs}}{{if gt $i 0}}, {{end}}ret{{$i}}{{end}}}
{{- end}}
if err != nil {
RespondWithError(w, err)
return
}
{{- if .Outputs | len}}
respBody, err := json.Marshal(respContent)
if err != nil {
err = WrapError(ErrInternal, err, "failed to marshal json response")
RespondWithError(w, err)
return
}
{{- end}}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
{{- if .Outputs | len}}
w.Write(respBody)
{{- else }}
w.Write([]byte("{}"))
{{- end}}
}
{{end}}
{{end -}}
func RespondWithError(w http.ResponseWriter, err error) {
rpcErr, ok := err.(Error)
if !ok {
rpcErr = WrapError(ErrInternal, err, "webrpc error")
}
statusCode := HTTPStatusFromErrorCode(rpcErr.Code())
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
respBody, _ := json.Marshal(rpcErr.Payload())
w.Write(respBody)
}
{{- end -}}
{{- end -}}