I'm reading json data from a file and sending it to a remote server using gob encoding, but I'm not happy with my code, I tried several ways to get a more generic function, but I'm failed, the only way that my code works is having identical functions for every type.
I tried using switch for types, but in the same way is needed repeat code in order to unmarshall and encode gob data
Please, could somebody help me to understand how improve that?
Two types:
type Data1 struct{
ID int
Message string
}
type Data2 struct{
Serial int
Height float64
Loss float64
Temp float64
Oil float64
}
Function for Data1 type
func SenderData1(address string, buff *filebuffer.Buffer) {
var conn net.Conn
var err error
var line string
var obj Data1
for {
line, err = buff.Pop()
if err != nil {
log.Critical("Error Poping:", err.Error())
continue
}
if len(line) == 0 {
time.Sleep(1 * time.Second)
continue
}
if err := json.Unmarshal([]byte(line), &obj); err != nil {
log.Critical("Error Unmarshaling:", err.Error())
continue
}
for {
log.Info("Trying to connect with Server...")
conn, err = net.Dial(PROTO, address)
// If err try to connect again
if err != nil {
log.Error("Error connecting:", err.Error())
time.Sleep(1 * time.Second)
continue
}
// If connected break the loop
break
}
log.Debug("Sending ", obj, " to:", address)
encoder := gob.NewEncoder(conn)
err := encoder.Encode(obj)
if err != nil {
log.Critical("Error Encoding Gob:", err.Error())
}
// Timer between every sending, ie. Reading from buffer
time.Sleep(300 * time.Millisecond)
conn.Close()
}
}
The same function but for Data2 type
func SenderData2(address string, buff *filebuffer.Buffer) {
var conn net.Conn
var err error
var line string
var obj Data2
for {
line, err = buff.Pop()
if err != nil {
log.Critical("Error Poping:", err.Error())
continue
}
if len(line) == 0 {
time.Sleep(1 * time.Second)
continue
}
if err := json.Unmarshal([]byte(line), &obj); err != nil {
log.Critical("Error Unmarshaling:", err.Error())
continue
}
for {
log.Info("Trying to connect with Server...")
conn, err = net.Dial(PROTO, address)
// If err try to connect again
if err != nil {
log.Error("Error connecting:", err.Error())
time.Sleep(1 * time.Second)
continue
}
// If connected break the loop
break
}
log.Debug("Sending ", obj, " to:", address)
encoder := gob.NewEncoder(conn)
err := encoder.Encode(obj)
if err != nil {
log.Critical("Error Encoding Gob:", err.Error())
}
// Timer between every sending, ie. Reading from buffer
time.Sleep(300 * time.Millisecond)
conn.Close()
}