-
Notifications
You must be signed in to change notification settings - Fork 0
/
operation.go
183 lines (143 loc) · 3.74 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
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
package goapi
import (
"fmt"
"net/http"
"net/url"
"reflect"
"strings"
"github.com/NaturalSelectionLabs/goapi/lib/middlewares"
"github.com/NaturalSelectionLabs/goapi/lib/openapi"
"github.com/naturalselectionlabs/vary"
)
// OperationHandler is a function to handle input and output of a http operation.
type OperationHandler any
// Operation is a handler for a specific HTTP method and path.
// We use reflection to constrain the handler function signature,
// to make it follow the openapi spec.
type Operation struct {
group *Group
method openapi.Method
path *Path
name string
vHandler reflect.Value
tHandler reflect.Type
params []*parsedParam
tRes reflect.Type
override http.HandlerFunc
configOpenAPI ConfigOpenAPI
}
func (g *Group) newOperation(method openapi.Method, path string, handler OperationHandler) *Operation {
optionalSlash := true
for _, op := range g.router.operations {
if path == strings.TrimRight(op.path.path, "/") {
optionalSlash = false
}
}
p, err := newPath(path, optionalSlash)
if err != nil {
panic(err)
}
if h, ok := handler.(func(http.ResponseWriter, *http.Request)); ok {
return &Operation{
group: g,
method: method,
path: p,
override: h,
}
}
vHandler := reflect.ValueOf(handler)
tHandler := vHandler.Type()
var name string
if tHandler.Kind() == reflect.Func {
name = toOperationName(fnName(handler))
} else {
panic("handler must be a function or a struct with Handle method")
}
params := []*parsedParam{}
for i := 0; i < tHandler.NumIn(); i++ {
params = append(params, parseParam(g.router.Schemas, p, tHandler.In(i)))
}
if tHandler.NumOut() != 1 {
panic("handler must return a single value")
}
tRes := tHandler.Out(0)
return &Operation{
group: g,
method: method,
path: p,
name: name,
vHandler: vHandler,
tHandler: tHandler,
params: params,
tRes: tRes,
}
}
// Handler implements the [middlewares.Middleware] interface.
func (op *Operation) Handler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != op.method.String() {
next.ServeHTTP(w, r)
return
}
params := op.path.match(r.URL.Path)
if params == nil {
next.ServeHTTP(w, r)
return
}
if op.override != nil {
op.override(w, r)
return
}
qs := r.URL.Query()
for k, v := range params {
qs.Set(k, v)
}
op.handle(w, r, qs)
})
}
func (op *Operation) handle(w http.ResponseWriter, r *http.Request, qs url.Values) {
params := []reflect.Value{}
for _, p := range op.params {
if p.isContext {
params = append(params, reflect.ValueOf(r.Context()))
continue
}
if p.isRequest {
params = append(params, reflect.ValueOf(r))
continue
}
var param reflect.Value
var err error
switch p.in {
case inHeader:
param, err = p.loadHeader(r.Header)
case inURL:
param, err = p.loadURL(qs)
case inBody:
param, err = p.loadBody(r.Body)
}
if err != nil {
middlewares.ResponseError(w, http.StatusBadRequest, &openapi.Error{
Code: openapi.CodeInvalidParam,
Message: err.Error(),
})
return
}
params = append(params, param)
}
res := op.vHandler.Call(params)[0]
resType := res.Type()
if resType.Kind() == reflect.Interface {
setType := resType
res = res.Elem()
resType = res.Type()
if _, ok := Interfaces[vary.ID(setType)]; !ok {
panic(fmt.Sprintf("handler response of path `%s` must goapi.Interface(new(%s))", op.path.path, setType.String()))
}
if _, ok := Interfaces[vary.ID(setType)].Implementations[vary.ID(resType)]; !ok {
panic(fmt.Sprintf("handler response of path `%s` must goapi.Interface(new(%s), %s{})",
op.path.path, setType.String(), resType.String()))
}
}
op.parseResponse(resType).write(w, res)
}