data_sender_go/data_sender.go
insanity@loafle.com 7193e723e7 data_sender
2017-04-26 15:47:40 +09:00

77 lines
1.3 KiB
Go

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
}