Using cancellations and timeouts in servers
Network servers usually start a new context when a new request is received. Usually, the server cancels the context when the requester closes the connection. Most HTTP frameworks, including the standard library, follow this basic pattern. If you are writing your own TCP server, you have to implement it yourself.
How to do it...
These are the steps to handle network connections with a timeout or cancellation:
- When you accept a network connection, create a new context with a cancellation or timeout:
- Ensure the context is canceled eventually.
- Pass the context to the handler:
ln, err:=net.Listen("tcp",":8080") if err!=nil { return err } for { conn, err:=ln.Accept() if err!=nil { return err } go func(c net.Conn) { // Step 1: // Request times out after duration:...