data_sender

This commit is contained in:
insanity@loafle.com 2017-04-26 15:47:40 +09:00
commit 7193e723e7
2 changed files with 103 additions and 0 deletions

77
data_sender.go Normal file
View File

@ -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
}

26
data_sender_test.go Normal file
View File

@ -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())
}