-
Notifications
You must be signed in to change notification settings - Fork 17
/
router.go
254 lines (205 loc) · 7.93 KB
/
router.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
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
//go:build go1.18
package main
import (
"context"
"errors"
"log"
"net/http"
"reflect"
"strings"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/rs/cors"
"github.com/swaggest/jsonschema-go"
oapi "github.com/swaggest/openapi-go"
"github.com/swaggest/openapi-go/openapi31"
"github.com/swaggest/rest"
"github.com/swaggest/rest/nethttp"
"github.com/swaggest/rest/response"
"github.com/swaggest/rest/response/gzip"
"github.com/swaggest/rest/web"
swgui "github.com/swaggest/swgui/v5emb"
"github.com/swaggest/usecase"
)
func NewRouter() http.Handler {
r := openapi31.NewReflector()
s := web.NewService(r)
s.OpenAPISchema().SetTitle("Advanced Example")
s.OpenAPISchema().SetDescription("This app showcases a variety of features.")
s.OpenAPISchema().SetVersion("v1.2.3")
jsr := s.OpenAPIReflector().JSONSchemaReflector()
jsr.DefaultOptions = append(jsr.DefaultOptions, jsonschema.InterceptDefName(
func(t reflect.Type, defaultDefName string) string {
return strings.ReplaceAll(defaultDefName, "GenericOpenapi31", "")
},
))
// Usecase middlewares can be added to web.Service or chirouter.Wrapper.
s.Wrap(nethttp.UseCaseMiddlewares(usecase.MiddlewareFunc(func(next usecase.Interactor) usecase.Interactor {
var (
hasName usecase.HasName
name = "unknown"
)
if usecase.As(next, &hasName) {
name = hasName.Name()
}
return usecase.Interact(func(ctx context.Context, input, output interface{}) error {
err := next.Interact(ctx, input, output)
if err != nil && !errors.Is(err, rest.HTTPCodeAsError(http.StatusNotModified)) {
log.Printf("usecase %s request (%+v) failed: %v\n", name, input, err)
}
return err
})
})))
// An example of global schema override to disable additionalProperties for all object schemas.
jsr.DefaultOptions = append(jsr.DefaultOptions,
jsonschema.InterceptSchema(func(params jsonschema.InterceptSchemaParams) (stop bool, err error) {
// Allow unknown request headers and skip response.
if oc, ok := oapi.OperationCtx(params.Context); !params.Processed || !ok ||
oc.IsProcessingResponse() || oc.ProcessingIn() == oapi.InHeader {
return false, nil
}
schema := params.Schema
if schema.HasType(jsonschema.Object) && len(schema.Properties) > 0 && schema.AdditionalProperties == nil {
schema.AdditionalProperties = (&jsonschema.SchemaOrBool{}).WithTypeBoolean(false)
}
return false, nil
}),
)
// Create custom schema mapping for 3rd party type.
uuidDef := jsonschema.Schema{}
uuidDef.AddType(jsonschema.String)
uuidDef.WithFormat("uuid")
uuidDef.WithExamples("248df4b7-aa70-47b8-a036-33ac447e668d")
jsr.AddTypeMapping(uuid.UUID{}, uuidDef)
// When multiple structures can be returned with the same HTTP status code, it is possible to combine them into a
// single schema with such configuration.
s.OpenAPICollector.CombineErrors = "anyOf"
s.Wrap(
// Example middleware to set up custom error responses and disable response validation for particular handlers.
func(handler http.Handler) http.Handler {
var h *nethttp.Handler
if nethttp.HandlerAs(handler, &h) {
h.MakeErrResp = func(ctx context.Context, err error) (int, interface{}) {
code, er := rest.Err(err)
var ae anotherErr
if errors.As(err, &ae) {
return http.StatusBadRequest, ae
}
return code, customErr{
Message: er.ErrorText,
Details: er.Context,
}
}
var hr rest.HandlerWithRoute
if h.RespValidator != nil &&
nethttp.HandlerAs(handler, &hr) {
if hr.RoutePattern() == "/json-body-manual/{in-path}" || hr.RoutePattern() == "/json-body/{in-path}" {
h.RespValidator = nil
}
}
}
return handler
},
// Example middleware to set up CORS headers.
// See https://pkg.go.dev/github.com/rs/cors for more details.
cors.AllowAll().Handler,
// Response validator setup.
//
// It might be a good idea to disable this middleware in production to save performance,
// but keep it enabled in dev/test/staging environments to catch logical issues.
response.ValidatorMiddleware(s.ResponseValidatorFactory),
gzip.Middleware, // Response compression with support for direct gzip pass through.
)
// Annotations can be used to alter documentation of operation identified by method and path.
s.OpenAPICollector.AnnotateOperation(http.MethodPost, "/validation", func(oc oapi.OperationContext) error {
o3, ok := oc.(openapi31.OperationExposer)
if !ok {
return nil
}
op := o3.Operation()
if op.Description != nil {
*op.Description = *op.Description + " Custom annotation."
}
return nil
})
s.Get("/query-object", queryObject())
s.Post("/form", form())
s.Post("/file-upload", fileUploader())
s.Post("/file-multi-upload", fileMultiUploader())
s.Get("/json-param/{in-path}", jsonParam())
s.Post("/json-body/{in-path}", jsonBody(),
nethttp.SuccessStatus(http.StatusCreated))
s.Post("/json-body-manual/{in-path}", jsonBodyManual(),
nethttp.SuccessStatus(http.StatusCreated))
s.Post("/json-body-validation/{in-path}", jsonBodyValidation())
s.Post("/json-slice-body", jsonSliceBody())
s.Post("/json-map-body", jsonMapBody(),
// Annotate operation to add post-processing if necessary.
nethttp.AnnotateOpenAPIOperation(func(oc oapi.OperationContext) error {
oc.SetDescription("Request with JSON object (map) body.")
return nil
}))
s.Get("/html-response/{id}", htmlResponse(), nethttp.SuccessfulResponseContentType("text/html"))
s.Get("/output-headers", outputHeaders())
s.Head("/output-headers", outputHeaders())
s.Get("/output-csv-writer", outputCSVWriter(),
nethttp.SuccessfulResponseContentType("text/csv; charset=utf-8"))
s.Post("/req-resp-mapping", reqRespMapping(),
nethttp.RequestMapping(new(struct {
Val1 string `header:"X-Header"`
Val2 int `formData:"val2"`
})),
nethttp.ResponseHeaderMapping(new(struct {
Val1 string `header:"X-Value-1"`
Val2 int `header:"X-Value-2"`
})),
)
s.Post("/validation", validation())
s.Post("/no-validation", noValidation())
// Type mapping is necessary to pass interface as structure into documentation.
jsr.AddTypeMapping(new(gzipPassThroughOutput), new(gzipPassThroughStruct))
s.Get("/gzip-pass-through", directGzip())
s.Head("/gzip-pass-through", directGzip())
s.Get("/error-response", errorResponse())
s.Post("/text-req-body/{path}", textReqBody(), nethttp.RequestBodyContent("text/csv"))
s.Post("/text-req-body-ptr/{path}", textReqBodyPtr(), nethttp.RequestBodyContent("text/csv"))
// Security middlewares.
// - sessMW is the actual request-level processor,
// - sessDoc is a handler-level wrapper to expose docs.
sessMW := func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if c, err := r.Cookie("sessid"); err == nil {
r = r.WithContext(context.WithValue(r.Context(), "sessionID", c.Value))
}
handler.ServeHTTP(w, r)
})
}
sessDoc := nethttp.APIKeySecurityMiddleware(s.OpenAPICollector, "User",
"sessid", oapi.InCookie, "Session cookie.")
// Security schema is configured for a single top-level route.
s.With(sessMW, sessDoc).Method(http.MethodGet, "/root-with-session", nethttp.NewHandler(dummy()))
// Security schema is configured on a sub-router.
s.Route("/deeper-with-session", func(r chi.Router) {
r.Group(func(r chi.Router) {
r.Use(sessMW, sessDoc)
r.Method(http.MethodGet, "/one", nethttp.NewHandler(dummy()))
r.Method(http.MethodGet, "/two", nethttp.NewHandler(dummy()))
})
})
// You can also walk the spec and add more information.
for p, pi := range r.Spec.Paths.MapOfPathItemValues {
pi.Parameters = append(pi.Parameters, openapi31.ParameterOrReference{
Parameter: (&openapi31.Parameter{
In: openapi31.ParameterInHeader,
Name: "X-Umbrella-Header",
Schema: map[string]interface{}{
"type": "string",
},
}).WithDescription("This request header is supported in all operations."),
})
r.Spec.Paths.MapOfPathItemValues[p] = pi
}
// Swagger UI endpoint at /docs.
s.Docs("/docs", swgui.New)
return s
}