Bläddra i källkod

Add IsWebSocketUpgrade

Gary Burd 9 år sedan
förälder
incheckning
a622679ebd
2 ändrade filer med 25 tillägg och 0 borttagningar
  1. 7 0
      server.go
  2. 18 0
      server_test.go

+ 7 - 0
server.go

@@ -251,3 +251,10 @@ func Subprotocols(r *http.Request) []string {
 	}
 	return protocols
 }
+
+// IsWebSocketUpgrade returns true if the client requested upgrade to the
+// WebSocket protocol.
+func IsWebSocketUpgrade(r *http.Request) bool {
+	return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
+		tokenListContainsValue(r.Header, "Upgrade", "websocket")
+}

+ 18 - 0
server_test.go

@@ -31,3 +31,21 @@ func TestSubprotocols(t *testing.T) {
 		}
 	}
 }
+
+var isWebSocketUpgradeTests = []struct {
+	ok bool
+	h  http.Header
+}{
+	{false, http.Header{"Upgrade": {"websocket"}}},
+	{false, http.Header{"Connection": {"upgrade"}}},
+	{true, http.Header{"Connection": {"upgRade"}, "Upgrade": {"WebSocket"}}},
+}
+
+func TestIsWebSocketUpgrade(t *testing.T) {
+	for _, tt := range isWebSocketUpgradeTests {
+		ok := IsWebSocketUpgrade(&http.Request{Header: tt.h})
+		if tt.ok != ok {
+			t.Errorf("IsWebSocketUpgrade(%v) returned %v, want %v", tt.h, ok, tt.ok)
+		}
+	}
+}