-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler_special.go
52 lines (40 loc) · 1.24 KB
/
handler_special.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
// Experiment not stable
package httpu
import (
"encoding/json"
"fmt"
"net/http"
"reflect"
"strings"
)
type SpecialBase struct {
W http.ResponseWriter
R *http.Request
}
type SpecialInterface interface{}
type SpecialCreator func(*SpecialBase) SpecialInterface
type SHttpFunc func(...string) (interface{}, error)
// We will build a new interface and execute with Exec
func SpecialHandler(prefix string, create SpecialCreator, name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
obj := create(&SpecialBase{w, r})
method := reflect.ValueOf(obj).MethodByName(name).Interface().(func(...string) (interface{}, error))
handler := SpecialHandlerFunc(prefix, method)
handler(w, r)
})
}
// SpecialHandler Transform default HandlerFunc to our SHttpFunc
func SpecialHandlerFunc(prefix string, sfunc SHttpFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
spath := strings.TrimPrefix(r.URL.Path, prefix)
spath = strings.Trim(spath, "/")
params := strings.Split(spath, "/")
obj, err := sfunc(params...)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintln("Error:", err)))
return
}
json.NewEncoder(w).Encode(obj)
}
}