-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtypes.go
More file actions
205 lines (178 loc) · 9.61 KB
/
Copy pathtypes.go
File metadata and controls
205 lines (178 loc) · 9.61 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
package fiberoapi
import (
"reflect"
"github.com/gofiber/fiber/v3"
)
// OApiRouter interface that both OApiApp and OApiGroup implement
type OApiRouter interface {
GetApp() *OApiApp
GetPrefix() string
}
// OApiApp wraps fiber.App with OpenAPI capabilities
type OApiApp struct {
f *fiber.App
operations []OpenAPIOperation
config Config
notFoundInstalled bool // true once UseNotFoundHandler has installed the catch-all
}
// Implement OApiRouter interface for OApiApp
func (o *OApiApp) GetApp() *OApiApp {
return o
}
func (o *OApiApp) GetPrefix() string {
return ""
}
// Config returns the current configuration
func (o *OApiApp) Config() Config {
return o.config
}
// Use adds middleware to the OApiApp
func (o *OApiApp) Use(middleware fiber.Handler) {
o.f.Use(middleware)
}
// Listen starts the server on the given address
func (o *OApiApp) Listen(addr string) error {
return o.f.Listen(addr)
}
// HandlerFunc represents a handler function with typed input and output
type HandlerFunc[TInput any, TOutput any, TError any] func(c fiber.Ctx, input TInput) (TOutput, TError)
// PathInfo represents information about a path parameter
type PathInfo struct {
Name string
IsPath bool
Index int // Position in the path for validation
}
// ValidationErrorHandler is a function type for handling validation errors
// It receives the fiber context and the validation error, and returns a fiber error response
type ValidationErrorHandler func(c fiber.Ctx, err error) error
// AuthErrorHandler is a function type for handling authentication/authorization errors
// It receives the fiber context and the AuthError, and returns a fiber error response
type AuthErrorHandler func(c fiber.Ctx, err *AuthError) error
// Config represents configuration for the OApi wrapper
type Config struct {
EnableValidation bool // Enable request validation (default: true)
EnableOpenAPIDocs bool // Enable automatic docs setup (default: true)
EnableAuthorization bool // Enable authorization validation (default: false)
OpenAPIDocsPath string // Path for documentation UI (default: "/docs")
OpenAPIJSONPath string // Path for OpenAPI JSON spec (default: "/openapi.json")
OpenAPIYamlPath string // Path for OpenAPI YAML spec (default: "/openapi.yaml")
OpenAPITitle string // Title of the OpenAPI spec (default: "Fiber OpenAPI")
OpenAPIDescription string // Description of the OpenAPI spec (default: "API documentation generated by fiber-oapi")
OpenAPIVersion string // Version of the OpenAPI spec (default: "1.0.0")
AuthService AuthorizationService // Service for handling authentication and authorization
SecuritySchemes map[string]SecurityScheme // OpenAPI security schemes
DefaultSecurity []map[string][]string // Default security requirements
ValidationErrorHandler ValidationErrorHandler // Custom handler for validation errors
AuthErrorHandler AuthErrorHandler // Custom handler for auth errors (401/403/5xx)
NotFoundHandler fiber.Handler // Custom handler for unmatched routes. Receives a raw fiber.Ctx and owns the response (status + body). To reuse the library's envelope shape, call NotFoundEnvelope(c). Has no effect unless UseNotFoundHandler() is also called.
// DefaultErrorShape, when non-nil, replaces the built-in ErrorEnvelope
// across the library — both at runtime (parse, auth, 404/405 responses)
// and in the generated OpenAPI spec. Pass an empty/zero instance of any
// struct (or pointer-to-struct); the library fills its Code/StatusCode,
// Message/Description/Msg, Type, and Details fields per error category via
// reflection.
//
// Note: 422 validation responses intentionally keep the rich ErrorEnvelope
// shape (one entry per failing field) even when DefaultErrorShape is set.
// Leaving DefaultErrorShape nil keeps the default ErrorEnvelope everywhere.
DefaultErrorShape any
IncludeInvalidValueInErrors bool // Include offending value in default error envelope (default: false — may leak secrets)
}
// OpenAPIOptions represents options for OpenAPI operations
type OpenAPIOptions struct {
OperationID string `json:"operationId,omitempty"`
Tags []string `json:"tags,omitempty"`
Summary string `json:"summary,omitempty"`
Description string `json:"description,omitempty"`
Parameters []map[string]any `json:"parameters,omitempty"`
Security any `json:"security,omitempty"` // Can be []map[string][]string or "disabled"
RequiredRoles []string `json:"-"` // Roles required to access this route (OR semantics by default)
RequireAllRoles bool `json:"-"` // If true, all RequiredRoles must match (AND semantics)
RequiredPermissions []string `json:"-"` // Ex: ["document:read", "workspace:admin"]
ResourceType string `json:"-"` // Type de ressource concernée
// Hidden, when true, excludes this operation from the generated OpenAPI
// spec. The route is still registered on the underlying fiber.App and
// serves traffic normally — it just does not appear under paths in the
// generated JSON/YAML and any type only used by hidden operations does
// not leak into components.schemas. Useful for internal admin endpoints,
// in-progress routes, or anything you want to ship without publishing.
Hidden bool `json:"-"`
// Errors declares the custom error responses this operation can emit. Each
// entry is an instance of any struct (or pointer-to-struct) describing one
// error case. The library inspects each entry to populate the generated
// OpenAPI spec:
// - status code: from a HTTPStatus() int method, or from a "StatusCode"
// or "Code" int field (defaults to 500 if none found)
// - description: from a Description() string method, or from "Message",
// "Description", or "Msg" string fields (falls back to the HTTP reason
// phrase for the status code)
// - schema: generated from the entry's reflect.Type and shared via $ref
// when the type is named, so multiple entries with the same shape do
// not duplicate the schema
// - example: the entry value itself, marshalled as JSON
//
// At runtime the handler returns one of these instances via its TError
// generic parameter (which can be `error`, a concrete `*ErrorResponse`,
// or any other type) and the library emits it with the matching status.
Errors []any `json:"-"`
}
// OpenAPIOperation represents a registered operation
type OpenAPIOperation struct {
Method string
Path string
Options OpenAPIOptions
InputType reflect.Type
OutputType reflect.Type
ErrorType reflect.Type
}
type OpenAPIParameter struct {
Name string `json:"name"`
In string `json:"in"` // "path", "query", "header", "cookie"
Required bool `json:"required,omitempty"`
Description string `json:"description,omitempty"`
Schema map[string]any `json:"schema"`
}
type OpenAPIResponse struct {
Description string `json:"description"`
Content map[string]any `json:"content,omitempty"`
}
type OpenAPIRequestBody struct {
Description string `json:"description,omitempty"`
Required bool `json:"required,omitempty"`
Content map[string]any `json:"content"`
}
// ErrorResponse is the legacy flat error shape. Still emitted by handleCustomError
// when a handler returns a non-zero TError, so existing custom error types keep
// working. New code should prefer ErrorEnvelope, which is what the default
// validation / parse / auth handlers now produce.
type ErrorResponse struct {
Code int `json:"code"`
Details string `json:"details"`
Type string `json:"type"`
}
// ErrorEnvelope is the default response shape for validation, parsing and auth
// errors. It carries one entry per failing field plus a context block that lets
// callers correlate the response with their tracing setup.
type ErrorEnvelope struct {
Errors []ValidationErrorEntry `json:"errors"`
ResponseContext ResponseContext `json:"response_context"`
}
// ValidationErrorEntry describes a single failure (one field, one constraint).
// The same shape is used for body validation errors, JSON type mismatches and
// authentication / authorization failures so clients only have to parse one
// envelope.
type ValidationErrorEntry struct {
Type string `json:"type"` // validation_error | type_error | parse_error | authentication_error | authorization_error | not_found | method_not_allowed
Code int `json:"code"` // HTTP status code carried in the response
Loc []any `json:"loc"` // path to the field, e.g. ["body", "address", "zipcode"]
Field string `json:"field,omitempty"` // leaf field name, redundant with Loc but convenient
Msg string `json:"msg"` // human-readable message
Constraint string `json:"constraint,omitempty"` // failing rule, e.g. "min=11", "required", "email"
Value any `json:"value,omitempty"` // offending value (opt-in via Config.IncludeInvalidValueInErrors)
}
// ResponseContext carries metadata that helps a client correlate the response
// with their tracing setup. ResponseID mirrors the incoming X-Request-Id header
// when present, otherwise it is left empty.
type ResponseContext struct {
ResponseID string `json:"response_id,omitempty"`
}