-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
return_handler.go
79 lines (64 loc) · 1.85 KB
/
return_handler.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
// Copyright 2021 Flamego. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package flamego
import (
"net/http"
"reflect"
"github.com/flamego/flamego/inject"
)
// ReturnHandler is a service that is called when a route handler returns
// something. The ReturnHandler is responsible for writing to the ResponseWriter
// based on the values that are passed into this function.
type ReturnHandler func(Context, []reflect.Value)
func defaultReturnHandler() ReturnHandler {
canDeref := func(val reflect.Value) bool {
return val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr
}
isByteSlice := func(val reflect.Value) bool {
return val.Kind() == reflect.Slice && val.Type().Elem().Kind() == reflect.Uint8
}
return func(c Context, vals []reflect.Value) {
v := c.Value(inject.InterfaceOf((*http.ResponseWriter)(nil)))
w := v.Interface().(http.ResponseWriter)
var respVal reflect.Value
switch len(vals) {
case 1: // string, []byte, error
respVal = vals[0]
case 2:
// (int, string), (int, []byte), (int, error)
if vals[0].Kind() == reflect.Int {
w.WriteHeader(int(vals[0].Int()))
respVal = vals[1]
break
}
// (string, error), ([]byte, error)
if vals[0].Kind() == reflect.String || isByteSlice(vals[0]) {
respVal = vals[0]
if _, ok := vals[1].Interface().(error); ok {
respVal = vals[1]
}
break
}
}
if !respVal.IsValid() {
return
}
if err, ok := respVal.Interface().(error); ok && err != nil {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(err.Error()))
return
}
if respVal.IsZero() {
return
}
if canDeref(respVal) {
respVal = respVal.Elem()
}
if isByteSlice(respVal) {
_, _ = w.Write(respVal.Bytes())
} else {
_, _ = w.Write([]byte(respVal.String()))
}
}
}