From 7193e723e7e533d2592a41a461de4bf99d0ff2f7 Mon Sep 17 00:00:00 2001 From: "insanity@loafle.com" Date: Wed, 26 Apr 2017 15:47:40 +0900 Subject: [PATCH] data_sender --- data_sender.go | 77 +++++++++++++++++++++++++++++++++++++++++++++ data_sender_test.go | 26 +++++++++++++++ 2 files changed, 103 insertions(+) create mode 100644 data_sender.go create mode 100644 data_sender_test.go diff --git a/data_sender.go b/data_sender.go new file mode 100644 index 0000000..e74cb70 --- /dev/null +++ b/data_sender.go @@ -0,0 +1,77 @@ +package data_sender_go + +import ( + "google.golang.org/grpc" + _ "loafle.com/overflow/cron_go" + "log" + + pb "loafle.com/overflow/crawler_go/grpc" + "context" + "os" +) + +const ( + CENTRAL_ADDR = "127.0.0.1:50052" + FILE_PATH = "/home/insanity/data/temp" +) + +func Send(data []byte) { + conn, err := grpc.Dial(CENTRAL_ADDR, grpc.WithInsecure()) + if err != nil { + saveFailedData(data) + return + } + defer conn.Close() + + //temporary + client := pb.NewStatusClient(conn) + out, err := client.Status(context.Background(), &pb.Empty{}) + if err != nil { + saveFailedData(data) + return + } + log.Print(out) +} + +func saveFailedData(data []byte) { + + file, err := tempFile() + if err != nil { + log.Println(err) + } + defer func() { + if err := file.Close(); err != nil { + log.Println(err) + return + } + }() + + _, err = file.Write(data) + if err != nil { + log.Println(err) + } +} + +func tempFile() (*os.File, error) { + + var file *os.File + var fileInfo os.FileInfo + var err error + if fileInfo, err = os.Stat(FILE_PATH); err != nil { + if os.IsNotExist(err) { + file, err = os.Create(FILE_PATH) + if err != nil { + return nil, err + } + } + }else { + if fileInfo != nil { + file, err = os.OpenFile(FILE_PATH, os.O_RDWR|os.O_APPEND, 0660); + if err != nil { + return nil, err + } + } + } + + return file, nil +} \ No newline at end of file diff --git a/data_sender_test.go b/data_sender_test.go new file mode 100644 index 0000000..af790e3 --- /dev/null +++ b/data_sender_test.go @@ -0,0 +1,26 @@ +package data_sender_go + +import ( + "testing" + "loafle.com/overflow/crawler_go/grpc" + "time" + "bytes" + "encoding/binary" + "fmt" +) + +func TestSend(t *testing.T) { + result := &grpc.Output{ + StartDate:time.Now().UnixNano(), + EndDate:time.Now().UnixNano(), + Data:[]byte{'a','b','c'}, + } + + var buf bytes.Buffer + binary.Write(&buf, binary.BigEndian, result) + + fmt.Println(buf.Bytes()) + Send(buf.Bytes()) + +} +