Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hijack connection through http.ResponseController in http upgrader #181

Merged
merged 1 commit into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions hijack_go119.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//go:build !go1.20
// +build !go1.20

package ws

import (
"bufio"
"net"
"net/http"
)

func hijack(w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, error) {
hj, ok := w.(http.Hijacker)
if ok {
return hj.Hijack()
}
return nil, nil, ErrNotHijacker
}
19 changes: 19 additions & 0 deletions hijack_go120.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
//go:build go1.20
// +build go1.20

package ws

import (
"bufio"
"errors"
"net"
"net/http"
)

func hijack(w http.ResponseWriter) (net.Conn, *bufio.ReadWriter, error) {
conn, rw, err := http.NewResponseController(w).Hijack()
if errors.Is(err, http.ErrNotSupported) {
return nil, nil, ErrNotHijacker
}
return conn, rw, err
}
7 changes: 1 addition & 6 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,12 +155,7 @@ type HTTPUpgrader struct {
func (u HTTPUpgrader) Upgrade(r *http.Request, w http.ResponseWriter) (conn net.Conn, rw *bufio.ReadWriter, hs Handshake, err error) {
// Hijack connection first to get the ability to write rejection errors the
// same way as in Upgrader.
hj, ok := w.(http.Hijacker)
if ok {
conn, rw, err = hj.Hijack()
} else {
err = ErrNotHijacker
}
conn, rw, err = hijack(w)
if err != nil {
httpError(w, err.Error(), http.StatusInternalServerError)
return conn, rw, hs, err
Expand Down