-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmuxplus.go
90 lines (60 loc) · 1.53 KB
/
muxplus.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
package muxplus
import (
"github.com/gorilla/mux"
"net/http"
"reflect"
"github.com/go-playground/form"
"encoding/json"
"io/ioutil"
"fmt"
"strings"
)
type FuncVal struct {
Func *Func
Args []reflect.Value
Outs []reflect.Value
}
func HandleFuncPlus(router *mux.Router, path string, function interface{}, handler Handler) *mux.Route {
//解析func
f := FuncParse(function)
return router.HandleFunc(path, func(w http.ResponseWriter, req *http.Request) {
var (
err error
fv = FuncVal{Func: f}
)
if err = req.ParseForm(); err != nil {
http.Error(w, "bad request", http.StatusBadRequest)
return
}
handler.Deal(w, req, &fv)
})
}
func DefaultArgsParseHandler(handler Handler) Handler {
return HandlerFunc(func(w http.ResponseWriter, req *http.Request, fv *FuncVal) {
var (
err error
ctx = req.Context()
)
fv.Args = append(fv.Args, reflect.ValueOf(ctx))
if len(fv.Func.In) > 1 {
opts := reflect.New(fv.Func.In[1].Elem()).Interface()
contentType := req.Header.Get("Content-Type")
if strings.Contains(contentType, "application/json") {
var bytes []byte
defer req.Body.Close()
if bytes, err = ioutil.ReadAll(req.Body); err == nil {
fmt.Println("=====================", string(bytes))
err = json.Unmarshal(bytes, opts)
}
} else {
err = form.NewDecoder().Decode(opts, req.Form)
}
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fv.Args = append(fv.Args, reflect.ValueOf(opts))
}
handler.Deal(w, req, fv)
})
}