From 132f52ecbd35f03334cf2ca62ebd3cb9bcb38d47 Mon Sep 17 00:00:00 2001 From: Frederico Date: Sat, 6 Feb 2021 16:57:32 +0100 Subject: [PATCH] update 03.3md with proper code block syntax --- en/03.3.md | 52 +++++++++++++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/en/03.3.md b/en/03.3.md index eab33521..b0dc7f71 100644 --- a/en/03.3.md +++ b/en/03.3.md @@ -34,36 +34,38 @@ In the previous section we saw that Go uses `ListenAndServe` to handle these ste Let's take a look at the `http` package's source code. - //Build version go1.1.2. - func (srv *Server) Serve(l net.Listener) error { - defer l.Close() - var tempDelay time.Duration // how long to sleep on accept failure - for { - rw, e := l.Accept() - if e != nil { - if ne, ok := e.(net.Error); ok && ne.Temporary() { - if tempDelay == 0 { - tempDelay = 5 * time.Millisecond - } else { - tempDelay *= 2 - } - if max := 1 * time.Second; tempDelay > max { - tempDelay = max - } - log.Printf("http: Accept error: %v; retrying in %v", e, tempDelay) - time.Sleep(tempDelay) - continue +```go +//Build version go1.1.2. +func (srv *Server) Serve(l net.Listener) error { + defer l.Close() + var tempDelay time.Duration // how long to sleep on accept failure + for { + rw, e := l.Accept() + if e != nil { + if ne, ok := e.(net.Error); ok && ne.Temporary() { + if tempDelay == 0 { + tempDelay = 5 * time.Millisecond + } else { + tempDelay *= 2 } - return e - } - tempDelay = 0 - c, err := srv.newConn(rw) - if err != nil { + if max := 1 * time.Second; tempDelay > max { + tempDelay = max + } + log.Printf("http: Accept error: %v; retrying in %v", e, tempDelay) + time.Sleep(tempDelay) continue } - go c.serve() + return e } + tempDelay = 0 + c, err := srv.newConn(rw) + if err != nil { + continue + } + go c.serve() } +} +``` How do we accept client requests after we begin listening to a port? In the source code, we can see that `srv.Serve(net.Listener)` is called to handle client requests. In the body of the function there is a `for{}`. It accepts a request, creates a new connection then starts a new goroutine, passing the request data to the `go c.serve()` goroutine. This is how Go supports high concurrency, and every goroutine is independent.