-
Notifications
You must be signed in to change notification settings - Fork 0
/
gorpc.go
71 lines (51 loc) · 1.23 KB
/
gorpc.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
package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
type GoRPC struct {
funcMap *GoRpcFuncMap
}
func (rpc *GoRPC) New(route string, funcMap *GoRpcFuncMap) {
rpc.funcMap = funcMap
http.HandleFunc(route, func(w http.ResponseWriter, r *http.Request) {
if !corsMiddleware(w, r) {
return
}
if r.Method != http.MethodPost {
fmt.Println("Method not allowed", r.Method)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
rpc.HandleRPC(w, r)
})
}
func (rpc *GoRPC) HandleRPC(w http.ResponseWriter, r *http.Request) {
fmt.Println("New GoRpc Request: ", r.Method)
reqBody, e := io.ReadAll(r.Body)
fmt.Println("reqBody: ", string(reqBody))
if e != nil {
fmt.Println("reqBody error: ", e)
}
var goRpcRequest GoRpcRequest
json.Unmarshal(reqBody, &goRpcRequest)
fmt.Println("JSON REQUEST: ", goRpcRequest.Method)
fmt.Println("JSON REQUEST: ", goRpcRequest.Params)
handler := *rpc.funcMap
value, err := handler[goRpcRequest.Method](goRpcRequest.Params)
var response *GoRpcResponse
if err != nil {
response = &GoRpcResponse{
Success: false,
Data: err.Message,
}
} else {
response = &GoRpcResponse{
Success: true,
Data: value,
}
}
json.NewEncoder(w).Encode(response)
}