/
io.go
78 lines (65 loc) · 1.56 KB
/
io.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
package main
import (
"context"
"encoding/json"
"os"
"path/filepath"
"time"
"github.com/schwarzlichtbezirk/pds/pb"
"google.golang.org/grpc/grpclog"
)
// ReadDataFile reads ports.json file step by step,
// and sends readed ports to gRPC stream.
func ReadDataFile(fname string) (err error) {
grpclog.Infof("read file '%s'\n", fname)
var f *os.File
if f, err = os.Open(filepath.Join(ConfigPath, fname)); err != nil {
return
}
defer f.Close()
// limit execution time of the action
var ctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// inits gRPC stream
var stream pb.PortGuide_RecordListClient
if stream, err = grpcClient.RecordList(ctx); err != nil {
return
}
// finally get stream result
defer func() {
var reply *pb.Summary
if reply, err = stream.CloseAndRecv(); err != nil {
return
}
grpclog.Infof("data base summary: readed %d ports, elapsed %dms",
reply.PortCount, reply.ElapsedTime)
}()
var dec = json.NewDecoder(f)
// read open bracket
if _, err = dec.Token(); err != nil {
return
}
// while the array contains values
for dec.More() {
var port pb.Port
// read and skip key token
if _, err = dec.Token(); err != nil {
return
}
// read port structure
if err = dec.Decode(&port); err != nil {
return
}
if err = stream.Send(&port); err != nil {
return
}
if len(port.Coordinates) != 2 {
grpclog.Warningf("port without coordinates: %s, %s\n", port.Unlocs[0], port.Name)
}
}
// read closing bracket
if _, err = dec.Token(); err != nil {
return
}
return nil
}