Skip to content

Commit

Permalink
Hijack connection through http.ResponseController in http upgrader (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
xakep666 authored Aug 9, 2023
1 parent 40c1550 commit fe40e5d
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 6 deletions.
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

0 comments on commit fe40e5d

Please sign in to comment.