Skip to content

Commit

Permalink
Implement http.ResponseWriter unwrapping like http.ResponseController
Browse files Browse the repository at this point in the history
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.

Fixes #455
  • Loading branch information
mafredri committed Aug 21, 2024
1 parent e46e020 commit d86cd75
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
2 changes: 1 addition & 1 deletion accept.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func accept(w http.ResponseWriter, r *http.Request, opts *AcceptOptions) (_ *Con
}
}

hj, ok := w.(http.Hijacker)
hj, ok := hijacker(w)
if !ok {
err = errors.New("http.ResponseWriter does not implement http.Hijacker")
http.Error(w, http.StatusText(http.StatusNotImplemented), http.StatusNotImplemented)
Expand Down
31 changes: 31 additions & 0 deletions hijack.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package websocket

import (
"net/http"
)

type rwUnwrapper interface {

Check failure on line 7 in hijack.go

View workflow job for this annotation

GitHub Actions / lint

type rwUnwrapper is unused (U1000)

Check failure on line 7 in hijack.go

View workflow job for this annotation

GitHub Actions / lint

type rwUnwrapper is unused (U1000)
Unwrap() http.ResponseWriter
}

// hijacker returns the Hijacker interface of the http.ResponseWriter.
// It follows the Unwrap method of the http.ResponseWriter if available,
// matching the behavior of http.ResponseController. If the Hijacker
// interface is not found, it returns false.
//
// Since the http.ResponseController is not available in Go 1.19, and
// does not support checking the presence of the Hijacker interface,
// this function is used to provide a consistent way to check for the
// Hijacker interface across Go versions.
func hijacker(rw http.ResponseWriter) (http.Hijacker, bool) {

Check failure on line 20 in hijack.go

View workflow job for this annotation

GitHub Actions / lint

func hijacker is unused (U1000)

Check failure on line 20 in hijack.go

View workflow job for this annotation

GitHub Actions / lint

func hijacker is unused (U1000)
for {
switch t := rw.(type) {
case http.Hijacker:
return t, true
case rwUnwrapper:
rw = t.Unwrap()
default:
return nil, false
}
}
}

0 comments on commit d86cd75

Please sign in to comment.