/
controller.go
278 lines (246 loc) · 6.71 KB
/
controller.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Copyright 2020 Torben Schinke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package http
import (
"database/sql"
"encoding/json"
"fmt"
"github.com/golangee/reflectplus"
"net/http"
"reflect"
"strconv"
"strings"
)
// A Scanner is SQL scanner compatible, but only needs tp scan from a string
type Scanner interface {
Scan(src interface{}) error
}
type Controller struct {
}
// MustNewController asserts that ctr is useful controller and otherwise bails out.
func MustNewController(srv *Server, ctr interface{}) *Controller {
c, err := NewController(srv, ctr)
if err != nil {
panic(err)
}
return c
}
// NewController tries to create a http/rest presentation service/controller/layer from the given instance.
func NewController(srv *Server, ctr interface{}) (*Controller, error) {
res := &Controller{}
rtype := reflect.TypeOf(ctr)
if rtype.Kind() == reflect.Ptr {
rtype = rtype.Elem()
}
s := reflectplus.FindByType(rtype)
if s == nil {
return nil, fmt.Errorf("%v is not a known struct", rtype)
}
vtype := reflect.ValueOf(ctr)
meta, ok := s.(*reflectplus.Struct)
if !ok {
return nil, fmt.Errorf("%v must be a struct but is %v", rtype, reflect.TypeOf(s))
}
prefixRoutes := httpRoutes(meta.Annotations)
for _, m := range meta.Methods {
method := m
verbs := httpMethods(method.Annotations)
routes := httpRoutes(method.Annotations)
if len(verbs) == 0 {
continue
}
if len(routes) == 0 && len(prefixRoutes) == 0 {
continue
}
if len(routes) == 0 {
routes = append(routes, "/")
}
var refFunc reflect.Value
for i := 0; i < vtype.NumMethod(); i++ {
if vtype.Type().Method(i).Name == method.Name {
refFunc = vtype.Method(i)
break
}
}
if !refFunc.IsValid() {
panic("reflectplus data does not match actual reflect data: method '" + method.Name + "' not found")
}
methodParams, err := scanMethodParams(*meta, method)
if err != nil {
return nil, reflectplus.PositionalError(method, err)
}
for _, prefixRoute := range prefixRoutes {
for _, route := range routes {
for _, verb := range verbs {
path := joinPaths(prefixRoute, route)
fmt.Printf("registered route %s %s by %s \n", method.Name, path, reflectplus.PositionalError(method, nil).Error())
srv.handle(verb, path, func(writer http.ResponseWriter, request *http.Request, params KeyValues) error {
return routedFunc(method, refFunc, methodParams, writer, request, params)
})
}
}
}
}
return res, nil
}
func routedFunc(method reflectplus.Method, refFunc reflect.Value, methodParams []methodParam, writer http.ResponseWriter, request *http.Request, params KeyValues) error {
args := make([]reflect.Value, 0, len(method.Params))
fmt.Println(method.Name)
for _, p := range methodParams {
switch p.paramType {
case ptCtx:
args = append(args, reflect.ValueOf(request.Context()))
case ptPath:
parsedType, err := scanToType(params.ByName(p.Alias()), p.param.Type, refFunc.Type().In(p.idx))
if err != nil {
return err
}
args = append(args, reflect.ValueOf(parsedType))
case ptQuery:
url := request.URL
strValue := url.Query().Get(p.Alias())
parsedType, err := scanToType(strValue, p.param.Type, refFunc.Type().In(p.idx))
if err != nil {
return err
}
args = append(args, reflect.ValueOf(parsedType))
case ptHeader:
strValue := request.Header.Get(p.Alias())
parsedType, err := scanToType(strValue, p.param.Type, refFunc.Type().In(p.idx))
if err != nil {
return err
}
args = append(args, reflect.ValueOf(parsedType))
case ptRequest:
args = append(args, reflect.ValueOf(request))
case ptResponseWriter:
args = append(args, reflect.ValueOf(writer))
default:
panic("method parameter type " + strconv.Itoa(int(p.paramType)) + " not implemented")
}
}
res := refFunc.Call(args)
for _, v := range res {
if err, ok := v.Interface().(error); ok {
return err
}
}
// TODO how to process serialization responses?
for _, v := range res {
val := v.Interface()
if val == nil {
continue
}
b, err := json.Marshal(val)
if err != nil {
return err
}
writer.Header().Add("Content-Type", "application/json")
_, err = writer.Write(b)
if err != nil {
return err
}
}
return nil
}
func scanToType(src string, dst reflectplus.TypeDecl, dstType reflect.Type) (interface{}, error) {
if dst.ImportPath == "" {
switch dst.Identifier {
case "int":
i, err := strconv.ParseInt(src, 10, 64)
return int(i), err
case "int64":
i, err := strconv.ParseInt(src, 10, 64)
return int64(i), err
case "int32":
i, err := strconv.ParseInt(src, 10, 64)
return int32(i), err
case "byte":
i, err := strconv.ParseInt(src, 10, 64)
return byte(i), err
case "string":
return src, nil
case "float64":
i, err := strconv.ParseFloat(src, 64)
return i, err
case "bool":
i, err := strconv.ParseBool(src)
return i, err
default:
return nil, fmt.Errorf("scanToType: base type not supported: '%s' (%s)", dst.Identifier, dstType.String())
}
}
val := reflect.New(dstType)
obj := val.Interface()
if scanner, ok := obj.(sql.Scanner); ok {
err := scanner.Scan(src)
if dstType.Kind() != reflect.Ptr {
obj = val.Elem().Interface()
}
return obj, err
}
return nil, fmt.Errorf("unsupported type does not implement http.Scanner: %s", dstType.String())
}
func joinPaths(a, b string) string {
if a == "" && b == "" {
return "/"
}
if a == "" {
return b
}
if b == "" {
return a
}
sb := &strings.Builder{}
if !strings.HasPrefix(a, "/") {
sb.WriteString("/")
}
sb.WriteString(a)
if !strings.HasSuffix(a, "/") {
if strings.HasPrefix(b, "/") {
sb.WriteString(b)
} else {
sb.WriteString(b[1:])
}
}
p := sb.String()
if strings.HasSuffix(p, "/") {
return p[:len(p)-1]
}
return p
}
func httpMethods(annotations []reflectplus.Annotation) []string {
var res []string
for _, a := range annotations {
if a.Name == AnnotationMethod {
method := a.AsString("value")
if len(method) > 0 {
res = append(res, method)
}
}
}
return res
}
func httpRoutes(annotations []reflectplus.Annotation) []string {
var res []string
for _, a := range annotations {
if a.Name == AnnotationRoute {
v := a.AsString("value")
if len(v) > 0 {
res = append(res, v)
}
}
}
return res
}