Connect TCP to EOF in Go

I have the following:

    //In an init func
    if logStashHost != "" {
        lsconn, err = net.Dial("tcp", logStashHost)
    }
    ...
    ToLogStash(rec, lsconn)

Then Two functions:

func ReadLogStash(conn net.Conn) {
    buffer := make([]byte, 256)
    for {
        _, err := conn.Read(buffer)
        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Println(buffer)
        }
    }
}

func ToLogStash(r *logrow.Record, conn net.Conn) {
    b, err := json.Marshal(r)
    if err != nil {
        fmt.Println(err)
        return
    }
    _, err = fmt.Fprintln(conn, string(b))
    if err != nil {
        fmt.Println(err)
    }
}

Where ReadLogStash is a working goroutine. If the other side closes, I get EOF. What would be a good implementation in ReadLogStash to try to reconnect every X seconds when it receives EOF?

+4
source share
2 answers

Go has channels for synchronization and communication, use them!

Make your connection in a loop and wait for some message to return to the channel.

...
errCh := make(chan error)
for {
    lsconn, err = net.Dial("tcp", logStashHost)
    // check error!
    go ReadLogStash(lsconn, errCh)
    err = <-errCh
    if err != nil {
        // bad error
        break
    }
    // sleep to backoff on retries?
}
...

func ReadLogStash(conn net.Conn, errCh chan error) {
    _, err := io.Copy(os.Stderr, conn)
    if err != nil {
        fmt.Println(err)
    }
    // a nil error from io.Copy means you reached EOF.
    errCh <- err
}

If you have more functions in ReadLogStash, you might just use io.Copy inline and forget the whole function, but this template may come in handy for you anyway.

+5
source

Here's what I ended up with, the channel was in the right direction:

if logStashHost != "" {
    lsc = make(chan *logrow.Record)
    go ToLogStash(lsc, logStashHost)
}
...
if lsc != nil {
   lsc <- rec
}
...
func ToLogStash(c chan *logrow.Record, logStashHost string) {
    var lsconn net.Conn
    var enc *json.Encoder
    var err error
    connect := func() {
        for {
            lsconn, err = net.Dial("tcp", logStashHost)
            if err == nil {
                enc = json.NewEncoder(lsconn)
                break
            }
            log.Println(err)
            time.Sleep(time.Second)
        }
    }
    connect()
    for r := range c {
        err = enc.Encode(r)
        if err != nil {
            lsconn.Close()
            log.Println(err)
            connect()
        }
    }
}
+1

Source: https://habr.com/ru/post/1538782/


All Articles