Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 12cbf54

Browse files
committedAug 21, 2024·
Implement http.ResponseWriter unwrapping like http.ResponseController
Since we rely on the connection not being hijacked too early (i.e. detecting the presence of http.Hijacker) to set headers, we must manually implement the unwrapping of the http.ResponseController. By doing so, we also retain Go 1.19 compatibility without build tags. Closes #455
1 parent e46e020 commit 12cbf54

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed
 

‎accept.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ func accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (_ *Con
105105
}
106106
}
107107

108-
hj, ok := w.(http.Hijacker)
108+
hj, ok := hijacker(w)
109109
if !ok {
110110
err = errors.New("http.ResponseWriter does not implement http.Hijacker")
111111
http.Error(w, http.StatusText(http.StatusNotImplemented), http.StatusNotImplemented)

‎hijack.go

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//go:build !js
2+
3+
package websocket
4+
5+
import (
6+
"net/http"
7+
)
8+
9+
type rwUnwrapper interface {
10+
Unwrap() http.ResponseWriter
11+
}
12+
13+
// hijacker returns the Hijacker interface of the http.ResponseWriter.
14+
// It follows the Unwrap method of the http.ResponseWriter if available,
15+
// matching the behavior of http.ResponseController. If the Hijacker
16+
// interface is not found, it returns false.
17+
//
18+
// Since the http.ResponseController is not available in Go 1.19, and
19+
// does not support checking the presence of the Hijacker interface,
20+
// this function is used to provide a consistent way to check for the
21+
// Hijacker interface across Go versions.
22+
func hijacker(rw http.ResponseWriter) (http.Hijacker, bool) {
23+
for {
24+
switch t := rw.(type) {
25+
case http.Hijacker:
26+
return t, true
27+
case rwUnwrapper:
28+
rw = t.Unwrap()
29+
default:
30+
return nil, false
31+
}
32+
}
33+
}

0 commit comments

Comments
 (0)
Please sign in to comment.