If you try to read from the socket it may block, so I want to be able to cancel it with context.
I would like to write the following code if possible, but I can not do it, so make a note of the alternative
select {
case size, err := conn.Read():
// Abbreviation
case <-ctx.Done():
//略
}
Use Set Deadline like this.
Note that the response time to ctx.Done ()
may increase depending on the deadline setting time,
The response time request to ctx.Done () is often much looser than the response time request to Read, so it should be less of a problem.
continue_read := true
for continue_read {
err := conn.SetReadDeadline(time.Now().Add(time.Millisecond * 500))
if err != nil {
return err
}
size, err := conn.Read(buf)
switch {
case err == nil || os.IsTimeout(err):
continue_read = true // Do nothing
case errors.Is(err, io.EOF):
continue_read = false
default:
return err
}
//Write buf operations, etc.
select {
case <-ctx.Done():
return ctx.Err()
default:
}
}
Well, the problem has been solved, but it's not very beautiful, so I'd like to do something about it.
Recommended Posts