How to enable Read / Write of net.Conn with context with golang

motivation

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():
 //略
}

solution

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

How to enable Read / Write of net.Conn with context with golang
How to read problem data with paiza
Summary of how to write AWS Lambda
[Image recognition] How to read the result of automatic annotation with VoTT
How to read a CSV file with Python 2/3
[Python] How to read excel file with pandas
How to read an array with Python's ConfigParser
How to specify attributes with Mock of python
How to implement "named_scope" of RubyOnRails with Django
Summary of how to read numerical data with python [CSV, NetCDF, Fortran binary]
How to read PyPI
How to read JSON
How to write a list / dictionary type of Python3
How to output CSV of multi-line header with pandas
Try to get the contents of Word with Golang
[Python] How to deal with pandas read_html read error
How to infer MAP estimate of HMM with PyStruct
How to infer MAP estimate of HMM with OpenGM
How to learn structured SVM of ChainCRF with PyStruct
Summary of how to share state with multiple functions
[Python] Summary of eval / exec functions + How to write character strings with line breaks
Compress variables such as DataFrame with joblib instead of pickle to read and write
The 15th offline real-time I tried to solve the problem of how to write with python
Offline real-time how to write Python implementation example of E14
XPath Basics (2) -How to write XPath
How to write offline real time I tried to solve the problem of F02 with Python
How to update with SQLAlchemy?
How to cast with Theano
How to display a list of installable versions with pyenv
How to Alter with SQLAlchemy?
Write to csv with Python
How to write to update Datastore to async with Google Apps Engine
How to separate strings with','
Summary of how to write .proto files used in gRPC
How to RDP with Fedora31
How to read an Excel file (.xlsx) with Pandas [Python]
How to Delete with SQLAlchemy?
How to write offline real-time Solving E05 problems with Python
How to enable Keras Regressor to be saved with pickle or joblib
How to extract features of time series data with PySpark Basics
[Hugo] Summary of how to add pages to sites built with Learn
How to get the ID of Type2Tag NXP NTAG213 with nfcpy
How to make a command to read the configuration file with pyramid
Offline real-time how to write Python implementation example of E15 problem
Here's a brief summary of how to get started with Django
How to monitor the execution status of sqlldr with the pv command
Explain how to use TensorFlow 2.X with implementation of VGG16 / ResNet50
Node.js: How to kill offspring of a process started with child_process.fork ()
How to write a docstring to create a named tuple document with sphinx
How to write offline real time Solve F01 problems with Python
How to cancel RT with tweepy
How to write a Python class
Python: How to use async with
How to read e-Stat subregion data
[Python] Write to csv file with Python
Summary of how to use pandas.DataFrame.loc
How to write soberly in pandas
Flask reuse How to write html
How to use virtualenv with PowerShell
How to deal with imbalanced data
How to install python-pip with ubuntu20.04LTS