(ctx context.Context, cancel context.CancelFunc, counter *counter)
| 23 | ) |
| 24 | |
| 25 | func (server *Server) generateHandleWS(ctx context.Context, cancel context.CancelFunc, counter *counter) http.HandlerFunc { |
| 26 | once := new(int64) |
| 27 | |
| 28 | go func() { |
| 29 | select { |
| 30 | case <-counter.timer().C: |
| 31 | cancel() |
| 32 | case <-ctx.Done(): |
| 33 | } |
| 34 | }() |
| 35 | |
| 36 | return func(w http.ResponseWriter, r *http.Request) { |
| 37 | if server.options.Once { |
| 38 | success := atomic.CompareAndSwapInt64(once, 0, 1) |
| 39 | if !success { |
| 40 | http.Error(w, "Server is shutting down", http.StatusServiceUnavailable) |
| 41 | return |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | num := counter.add(1) |
| 46 | closeReason := "unknown reason" |
| 47 | |
| 48 | defer func() { |
| 49 | num := counter.done() |
| 50 | log.Printf( |
| 51 | "Connection closed: %s, reason: %s, connections: %d/%d", |
| 52 | r.RemoteAddr, closeReason, num, server.options.MaxConnection, |
| 53 | ) |
| 54 | |
| 55 | if server.options.Once { |
| 56 | cancel() |
| 57 | } |
| 58 | }() |
| 59 | |
| 60 | if int64(server.options.MaxConnection) != 0 { |
| 61 | if num > server.options.MaxConnection { |
| 62 | closeReason = "exceeding max number of connections" |
| 63 | return |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | log.Printf("New client connected: %s, connections: %d/%d", r.RemoteAddr, num, server.options.MaxConnection) |
| 68 | |
| 69 | if r.Method != "GET" { |
| 70 | http.Error(w, "Method not allowed", 405) |
| 71 | return |
| 72 | } |
| 73 | server.upgrader.ReadBufferSize = webtty.MaxBufferSize |
| 74 | server.upgrader.WriteBufferSize = webtty.MaxBufferSize |
| 75 | server.upgrader.EnableCompression = true |
| 76 | conn, err := server.upgrader.Upgrade(w, r, nil) |
| 77 | if err != nil { |
| 78 | closeReason = err.Error() |
| 79 | return |
| 80 | } |
| 81 | defer conn.Close() |
| 82 | conn.SetCompressionLevel(9) |
no test coverage detected