/
http.go
93 lines (77 loc) · 2.1 KB
/
http.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
package rpc
import (
"context"
"encoding/json"
"net/http"
"net/rpc"
"github.com/mlayerprotocol/go-mlayer/common/constants"
"github.com/mlayerprotocol/go-mlayer/configs"
// "net/rpc/jsonrpc"
)
type JsonRpc struct {
JsonRpcVersion string `json:"jsonrpc"`
Id int `json:"id"`
Method string `json:"method"`
Params []json.RawMessage `json:"params"`
}
type HttpService struct {
Ctx *context.Context
Cfg *configs.MainConfiguration
rpcClient *rpc.Client
}
func NewHttpService(mainCtx *context.Context) *HttpService {
cfg, _ := (*mainCtx).Value(constants.ConfigKey).(*configs.MainConfiguration)
return &HttpService{
Ctx: mainCtx,
Cfg: cfg,
}
}
func (p *HttpService) sendHttp(w http.ResponseWriter, r *http.Request) {
var jsonrpc JsonRpc
err := json.NewDecoder(r.Body).Decode(&jsonrpc)
payload := jsonrpc.Params
// var params interface{}
var reply RpcResponse
err = p.rpcClient.Call("RpcService."+jsonrpc.Method, payload[0], &reply)
if err != nil {
reply = RpcResponse{
Data: err,
Status: "failure",
}
}
jData, err := json.Marshal(reply)
if err != nil {
logger.Errorf("marshal json error::", err)
}
w.Header().Set("Content-Type", "application/json")
w.Write(jData)
}
// func (p *HttpService) serveJSONRPC(w http.ResponseWriter, req *http.Request) {
// // if req.Method != "CONNECT" {
// // http.Error(w, "method must be connect", 405)
// // return
// // }
// conn, _, err := w.(http.Hijacker).Hijack()
// if err != nil {
// http.Error(w, "internal server error", 500)
// return
// }
// defer conn.Close()
// io.WriteString(conn, "HTTP/1.0 Connected\r\n\r\n")
// jsonrpc.ServeConn(conn)
// }
func (p *HttpService) Start() error {
hostname := "localhost"
port := ":9521"
client, err := rpc.DialHTTP("tcp", hostname+port)
if err != nil {
logger.Errorf("Rpc Error::", err)
return err
}
logger.Info("Dial to rpc successful!")
p.rpcClient = client
http.HandleFunc("/", p.sendHttp)
// http.HandleFunc("/rpcendpoint", p.serveJSONRPC)
err = http.ListenAndServe(":"+p.Cfg.RPCHttpPort, nil)
return err
}