去http.Request.Conn.ActiveConn是一个地图,那么它会有并发地图问题吗?

go http.Request.Context.ActiveConn is a map, will it have concurrent map problem?

If there are many connections, I print the request.Context which is including a ActiveConn(map), will it have concurrent reading and writing map problem?

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "r.ctx: %#v, %+v", r.Context(), r.Context())
    })
    http.ListenAndServe(":1234", nil)
}

I use a webench to give a pressure test, it will fail because of concurrent map problem. So, is there any one who has the same problem? Because of this, I messed up the core service... ...

The whole purpose of Go's http server implementation is to handle concurrent connections, so I doubt you'll see concurrency issues in the implementation itself.

What's happening here is that when printing the whole r.Context() there, you end up accessing an internal field of Go's Server object without synchronizing access to it.

That causes the concurrent map read and map write error you end up seeing.

Simplest solution would be to replace this:

fmt.Fprintf(w, "r.ctx: %#v, %+v", r.Context(), r.Context())

With some custom function you write that takes that Context object and extracts the values that are relevant for you (like for example, any custom key/value you have added yourself to the Context).

More detailed explanation about that activeConn field

The activeConn you see when you print the whole r.Context() as doing there, comes from Go's Server type.

When preparing to listen for connections, the Server creates a base context in which it adds a reference to the Server itself:

https://github.com/golang/go/blob/master/src/net/http/server.go#L2894

func (srv *Server) Serve(l net.Listener) error {
    ....
    ctx := context.WithValue(baseCtx, ServerContextKey, srv)
    ....
}

So when printing the whole context, you end up printing that activeConn field:

https://github.com/golang/go/blob/master/src/net/http/server.go#L2582

activeConn map[*conn]struct{}

The Server implementation synchronizes access to that map when it needs to use it, for example here:

https://github.com/golang/go/blob/master/src/net/http/server.go#L2997

...

s.mu.Lock()
defer s.mu.Unlock()
if s.activeConn == nil {
    s.activeConn = make(map[*conn]struct{})
}

if add {
    s.activeConn[c] = struct{}{}
} else {
    delete(s.activeConn, c)
}
....