/
rpc.go
91 lines (69 loc) · 1.62 KB
/
rpc.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
package main
import (
"github.com/gorilla/mux"
"github.com/gorilla/rpc"
"github.com/gorilla/rpc/json"
"net/http"
)
import jsonEnc "encoding/json"
type CodeLocation struct {
Method string
Filename string
LineNumber int
}
type NestedTrace struct {
Message string
Stack []CodeLocation
CausedBy *NestedTrace
}
type LogRequest struct {
Message string
Properties map[string]string
Trace NestedTrace
}
type dbFunc func(db *Db)
type LogRequestService struct {
channel chan dbFunc
}
func CreateLogRequestService() *LogRequestService {
return &LogRequestService{make(chan dbFunc, 100)}
}
func (s *LogRequestService) ExecuteWithDb(fn func(db *Db)) {
s.channel <- fn
}
type LogReply struct {
Message string
}
func (s *LogRequestService) ApplyWithDb(db *Db) {
for {
fn := <-s.channel
fn(db)
}
}
func (s *LogRequestService) Log(r *http.Request, args *LogRequest, reply *LogReply) error {
reply.Message = "OK"
var err error
var traceAsBytes []byte
traceAsBytes, err = jsonEnc.Marshal(args.Trace)
if err != nil {
return err
}
var propertiesAsBytes []byte
propertiesAsBytes, err = jsonEnc.Marshal(args.Properties)
propertiesStr := string(propertiesAsBytes)
traceStr := string(traceAsBytes)
message := args.Message
s.ExecuteWithDb(func(db *Db) {
LogError(db, message, traceStr, propertiesStr)
})
return nil
}
func InitRpc(r *mux.Router, filename string) {
db := OpenDb(filename)
logReqService := CreateLogRequestService()
s := rpc.NewServer()
s.RegisterCodec(json.NewCodec(), "application/json")
s.RegisterService(logReqService, "Log")
go logReqService.ApplyWithDb(db)
r.Handle("/rpc", s)
}