-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
180 lines (162 loc) · 4.44 KB
/
server.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
package httprpc
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"reflect"
"strings"
"sync"
"unicode"
"unicode/utf8"
)
type Request struct {
Method string
}
type Request2 struct {
Params interface{}
Id string
}
type ErrorResponse struct {
Error string
}
type methodType struct {
sync.Mutex // protects counters
method reflect.Method
ArgType reflect.Type
ReplyType reflect.Type
numCalls uint
}
type service struct {
name string // name of service
rcvr reflect.Value // receiver of methods for the service
typ reflect.Type // type of the receiver
method map[string]*methodType // registered methods
}
type Server struct {
serviceMap map[string]*service
}
func NewServer() *Server {
return &Server{
serviceMap: make(map[string]*service),
}
}
var unusedError *error
var typeOfOsError = reflect.TypeOf(unusedError).Elem()
// Is this an exported - upper case - name?
func isExported(name string) bool {
rune, _ := utf8.DecodeRuneInString(name)
return unicode.IsUpper(rune)
}
// Is this type exported or a builtin?
func isExportedOrBuiltinType(t reflect.Type) bool {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
// PkgPath will be non-empty even for an exported type,
// so we need to check the type name as well.
return isExported(t.Name()) || t.PkgPath() == ""
}
func (server *Server) Register(impl interface{}) {
s := &service{}
s.typ = reflect.TypeOf(impl)
s.rcvr = reflect.ValueOf(impl)
s.name = reflect.Indirect(s.rcvr).Type().Name()
s.method = make(map[string]*methodType)
for m := 0; m < s.typ.NumMethod(); m++ {
method := s.typ.Method(m)
mtype := method.Type
mname := method.Name
if method.PkgPath != "" {
continue
}
// Method needs three ins: receiver, *args, *reply.
if mtype.NumIn() != 3 {
log.Println("method", mname, "has wrong number of ins:", mtype.NumIn())
continue
}
// First arg must be a pointer.
argType := mtype.In(1)
if argType.Kind() != reflect.Ptr {
log.Println(mname, "argument type not a pointer:", argType)
continue
}
if !isExportedOrBuiltinType(argType) {
log.Println(mname, "argument type not exported or local:", argType)
continue
}
// Second arg must be a pointer.
replyType := mtype.In(2)
if replyType.Kind() != reflect.Ptr {
log.Println("method", mname, "reply type not a pointer:", replyType)
continue
}
if !isExportedOrBuiltinType(replyType) {
log.Println("method", mname, "reply type not exported or local:", replyType)
continue
}
// Method needs one out: error.
if mtype.NumOut() != 1 {
log.Println("method", mname, "has wrong number of outs:", mtype.NumOut())
continue
}
if returnType := mtype.Out(0); returnType != typeOfOsError {
log.Println("method", mname, "returns", returnType.String(), "not os.Error")
continue
}
s.method[mname] = &methodType{method: method, ArgType: argType, ReplyType: replyType}
}
server.serviceMap[s.name] = s
log.Printf("%#v", s)
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
log.Printf("----------------\n")
req := &Request{}
data, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Println(err)
return
}
json.Unmarshal(data, req)
log.Printf("Request: %#v\n", req)
// Find the receiver object.
sname := strings.Split(req.Method, ".")
service, ok := s.serviceMap[sname[0]]
if !ok || len(sname) != 2 {
log.Println("No such service")
return
}
// Find the method.
method, ok := service.method[sname[1]]
if !ok {
log.Println("No such method")
return
}
function := method.method.Func
// Prepare params.
argv := reflect.New(method.ArgType.Elem())
req2 := &Request2{Params: argv.Interface()}
// Parse params (again, could be improved...)
json.Unmarshal(data, req2)
// Prepare reply object.
replyv := reflect.New(method.ReplyType.Elem())
// Call the function
returnVals := function.Call([]reflect.Value{service.rcvr, argv, replyv})
// Check for error returned.
errInter := returnVals[0].Interface()
errmsg := ""
out := make([]byte, 0, 0)
if errInter != nil {
errmsg = errInter.(error).Error()
out, _ = json.Marshal(ErrorResponse{errmsg})
} else {
out, _ = json.Marshal(replyv.Interface())
}
// Write output.
log.Printf(string(out) + "\n")
w.Write(out)
}