Skip to content

Commit

Permalink
Correctly parse X-Stream-Protocol-Version header
Browse files Browse the repository at this point in the history
Signed-off-by: Ted Yu <yuzhihong@gmail.com>
  • Loading branch information
tedyu committed Apr 4, 2020
1 parent 7233908 commit 8aada68
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
Expand Up @@ -114,14 +114,26 @@ func negotiateProtocol(clientProtocols, serverProtocols []string) string {
return ""
}

func commaSeparatedHeaderValues(header []string) []string {
var parsedClientProtocols []string
for i := range header {
for _, clientProtocol := range strings.Split(header[i], ",") {
if proto := strings.Trim(clientProtocol, " "); len(proto) > 0 {
parsedClientProtocols = append(parsedClientProtocols, proto)
}
}
}
return parsedClientProtocols
}

// Handshake performs a subprotocol negotiation. If the client did request a
// subprotocol, Handshake will select the first common value found in
// serverProtocols. If a match is found, Handshake adds a response header
// indicating the chosen subprotocol. If no match is found, HTTP forbidden is
// returned, along with a response header containing the list of protocols the
// server can accept.
func Handshake(req *http.Request, w http.ResponseWriter, serverProtocols []string) (string, error) {
clientProtocols := req.Header[http.CanonicalHeaderKey(HeaderProtocolVersion)]
clientProtocols := commaSeparatedHeaderValues(req.Header[http.CanonicalHeaderKey(HeaderProtocolVersion)])
if len(clientProtocols) == 0 {
return "", fmt.Errorf("unable to upgrade: %s is required", HeaderProtocolVersion)
}
Expand Down
Expand Up @@ -58,11 +58,22 @@ func TestHandshake(t *testing.T) {
expectedProtocol: "",
expectError: true,
},
"no common protocol with comma separated list": {
clientProtocols: []string{"c, d"},
serverProtocols: []string{"a", "b"},
expectedProtocol: "",
expectError: true,
},
"common protocol": {
clientProtocols: []string{"b"},
serverProtocols: []string{"a", "b"},
expectedProtocol: "b",
},
"common protocol with comma separated list": {
clientProtocols: []string{"b, c"},
serverProtocols: []string{"a", "b"},
expectedProtocol: "b",
},
}

for name, test := range tests {
Expand Down

0 comments on commit 8aada68

Please sign in to comment.