-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathoperation.go
67 lines (53 loc) · 1.72 KB
/
operation.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
package oas
import (
"context"
"net/http"
"github.com/go-openapi/spec"
)
type operationInfo struct {
operation *spec.Operation
// params include all applicable operation params, even those defined
// on the path operation belongs to.
params []spec.Parameter
// consumes is either operation-defined "consumes" property or spec-wide
// "consumes" property.
consumes []string
// produces is either operation-defined "produces" property or spec-wide
// "produces" property.
produces []string
}
// operationContext is a middleware that adds operation info to the request
// context and calls next.
type operationContext struct {
next http.Handler
}
func (mw *operationContext) ServeHTTP(w http.ResponseWriter, req *http.Request, oi operationInfo, ok bool) {
if ok {
req = withOperationInfo(req, oi)
}
mw.next.ServeHTTP(w, req)
}
type contextKeyOperationInfo struct{}
// withOperationInfo returns request with context value defining *spec.Operation.
func withOperationInfo(req *http.Request, info operationInfo) *http.Request {
return req.WithContext(
context.WithValue(req.Context(), contextKeyOperationInfo{}, info),
)
}
// getOperationInfo returns *spec.Operation from the request's context.
// In case of operation not found GetOperation returns nil.
func getOperationInfo(req *http.Request) (operationInfo, bool) {
op, ok := req.Context().Value(contextKeyOperationInfo{}).(operationInfo)
return op, ok
}
// mustOperationInfo returns *spec.Operation from the request's context.
// In case of operation not found MustOperation panics.
//
// nolint
func mustOperationInfo(req *http.Request) operationInfo {
op, ok := getOperationInfo(req)
if ok {
return op
}
panic("request has no OpenAPI operation spec in its context")
}