Repository navigation
Expand file tree
/
Copy pathconfigureapi.gotmpl
More file actions
235 lines (197 loc) · 7.63 KB
/
Copy pathconfigureapi.gotmpl
File metadata and controls
235 lines (197 loc) · 7.63 KB
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
{{"// Code generated by go-swagger; DO NOT EDIT."}}
{{ if .Copyright -}}{{ lineComment .Copyright -}}{{ end }}
package {{ .APIPackage }}
import (
"context"
"crypto/tls"
"net/http"
"log"
"fmt"
"github.com/go-openapi/errors"
"github.com/go-openapi/loads"
"github.com/go-openapi/runtime"
"github.com/go-openapi/runtime/middleware"
"github.com/go-openapi/runtime/security"
{{ imports .DefaultImports }}
{{ imports .Imports }}
)
{{ $package := .Package }}
type contextKey string
const AuthKey contextKey = "Auth"
{{- range .OperationGroups }}
//go:generate mockery --name {{ pascalize .Name}}API --inpackage
{{ lineComment (printf "%sAPI %s" (pascalize .Name) .Description) }}
type {{ pascalize .Name }}API interface {
{{- range .Operations }}
{{- if .Summary }}
{{ lineComment (printf "%s %s" (pascalize .Name) .Summary) }}
{{- else if .Description }}
{{ lineComment (printf "%s %s" (pascalize .Name) .Description) }}
{{- end }}
{{ pascalize .Name }}(ctx context.Context, params {{.Package}}.{{ pascalize .Name }}Params) middleware.Responder
{{- end }}
}
{{- end }}
// Config is configuration for Handler
type Config struct {
{{- range .OperationGroups }}
{{ pascalize .Name }}API
{{- end }}
Logger func(string, ...any)
// InnerMiddleware is for the handler executors. These do not apply to the swagger.json document.
// The middleware executes after routing but before authentication, binding and validation
InnerMiddleware func(http.Handler) http.Handler
// Authorizer is used to authorize a request after the Auth function was called using the "Auth*" functions
// and the principal was stored in the context in the "AuthKey" context value.
Authorizer func(*http.Request) error
{{- range .SecurityDefinitions }}
{{- if .IsBasicAuth }}
// Auth{{ pascalize .ID }} for basic authentication
Auth{{ pascalize .ID }} func(user string, password string) ({{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}, error)
{{- end }}
{{- if .IsAPIKeyAuth }}
// Auth{{ pascalize .ID }} Applies when the "{{ escapeDoubleQuoted .Name }}" {{ escapeDoubleQuoted .Source }} is set
Auth{{ pascalize .ID }} func(token string) ({{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}, error)
{{- end }}
{{- if .IsOAuth2 }}
// Auth{{ pascalize .ID }} for OAuth2 authentication
Auth{{ pascalize .ID }} func(token string, scopes []string) ({{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}, error)
{{- end }}
{{- end }}
// Authenticator to use for all APIKey authentication
APIKeyAuthenticator func(string, string, security.TokenAuthentication) runtime.Authenticator
// Authenticator to use for all Bearer authentication
BasicAuthenticator func(security.UserPassAuthentication) runtime.Authenticator
// Authenticator to use for all Basic authentication
BearerAuthenticator func(string, security.ScopedTokenAuthentication) runtime.Authenticator
{{- range .Consumes }}
{{- if .Implementation }}
// {{ pascalize .Name }}Consumer is a {{ .Name }} consumer that will replace the default if not nil.
{{ pascalize .Name }}Consumer runtime.Consumer
{{- end }}
{{- end }}
}
// Handler returns an http.Handler given the handler configuration
// It mounts all the business logic implementers in the right routing.
func Handler(c Config) (http.Handler, error) {
h, _, err := HandlerAPI(c)
return h, err
}
// HandlerAPI returns an http.Handler given the handler configuration
// and the corresponding *{{ pascalize .Name }} instance.
// It mounts all the business logic implementers in the right routing.
func HandlerAPI(c Config) (http.Handler, *{{.Package}}.{{ pascalize .Name }}API, error) {
spec, err := loads.Analyzed(swaggerCopy(SwaggerJSON), "")
if err != nil {
return nil, nil, fmt.Errorf("analyze swagger: %w", err)
}
api := {{.Package}}.New{{ pascalize .Name }}API(spec)
api.ServeError = errors.ServeError
api.Logger = c.Logger
if c.APIKeyAuthenticator != nil {
api.APIKeyAuthenticator = c.APIKeyAuthenticator
}
if c.BasicAuthenticator != nil {
api.BasicAuthenticator = c.BasicAuthenticator
}
if c.BearerAuthenticator != nil {
api.BearerAuthenticator = c.BearerAuthenticator
}
{{- range .Consumes }}
if c.{{ pascalize .Name }}Consumer != nil {
api.{{ pascalize .Name }}Consumer = c.{{ pascalize .Name }}Consumer
} else {
{{- if .Implementation }}
api.{{ pascalize .Name }}Consumer = {{ .Implementation }}
{{- else }}
api.{{ pascalize .Name }}Consumer = runtime.ConsumerFunc(func(r io.Reader, target any) error {
_ = r
_ = target
return errors.NotImplemented("{{.Name}} consumer has not yet been implemented")
})
{{- end }}
}
{{- end }}
{{- range .Produces }}
{{- if .Implementation }}
api.{{ pascalize .Name }}Producer = {{ .Implementation }}
{{- else }}
api.{{ pascalize .Name }}Producer = runtime.ProducerFunc(func(w io.Writer, data any) error {
_ = w
_ = data
return errors.NotImplemented("{{.Name}} producer has not yet been implemented")
})
{{- end }}
{{- end }}
{{- range .SecurityDefinitions }}
{{- if .IsBasicAuth }}
api.{{ pascalize .ID }}Auth = func(user string, password string) ({{if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
if c.Auth{{ pascalize .ID }} == nil {
{{- if eq .Principal "any" }}
return "", nil
{{- else }}
panic("you specified a custom principal type, but did not provide the authenticator to resolve a principal")
{{- end }}
}
return c.Auth{{ pascalize .ID }}(user, password)
}
{{- end }}
{{- if .IsAPIKeyAuth }}
api.{{ pascalize .ID }}Auth = func(token string) ({{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
if c.Auth{{ pascalize .ID }} == nil {
{{- if eq .Principal "any" }}
return token, nil
{{- else }}
panic("you specified a custom principal type, but did not provide the authenticator to resolve a principal")
{{- end }}
}
return c.Auth{{ pascalize .ID }}(token)
}
{{- end }}
{{- if .IsOAuth2 }}
api.{{ pascalize .ID }}Auth = func(token string, scopes []string) ({{ if .PrincipalIsNullable }}*{{ end }}{{.Principal}}, error) {
if c.Auth{{ pascalize .ID }} == nil {
{{- if eq .Principal "any" }}
return token, nil
{{- else }}
panic("you specified a custom principal type, but did not provide the authenticator to resolve a principal")
{{- end }}
}
return c.Auth{{ pascalize .ID }}(token, scopes)
}
{{- end }}
{{- end }}
{{- if .SecurityDefinitions }}
api.APIAuthorizer = authorizer(c.Authorizer)
{{- end }}
{{- range .Operations }}
api.{{if ne .Package $package}}{{pascalize .Package}}{{end}}{{ pascalize .Name }}Handler =
{{- .PackageAlias }}.{{ pascalize .Name }}HandlerFunc(func(params {{.PackageAlias}}.{{ pascalize .Name }}Params{{if .Authorized}}, principal {{ if .PrincipalIsNullable }}*{{ end }}{{ .Principal }}{{end}}) middleware.Responder {
ctx := params.HTTPRequest.Context()
{{- if .Authorized }}
ctx = storeAuth(ctx, principal)
{{- end }}
return c.{{pascalize .Name}}(ctx, params)
})
{{- end }}
api.ServerShutdown = func() { }
return api.Serve(c.InnerMiddleware), api, nil
}
// swaggerCopy copies the swagger json to prevent data races in runtime
func swaggerCopy(orig json.RawMessage) json.RawMessage {
c := make(json.RawMessage, len(orig))
copy(c, orig)
return c
}
// authorizer is a helper function to implement the runtime.Authorizer interface.
type authorizer func(*http.Request) error
func (a authorizer) Authorize(req *http.Request, principal any) error {
if a == nil {
return nil
}
ctx := storeAuth(req.Context(), principal)
return a(req.WithContext(ctx))
}
func storeAuth(ctx context.Context, principal any) context.Context {
return context.WithValue(ctx, AuthKey, principal)
}