-
Notifications
You must be signed in to change notification settings - Fork 619
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Issue #9: Add raw http proxy as an alternative websocket handler
- Loading branch information
1 parent
def5c6c
commit fe10842
Showing
2 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
package proxy | ||
|
||
import ( | ||
"io" | ||
"log" | ||
"net" | ||
"net/http" | ||
"net/url" | ||
) | ||
|
||
// newRawProxy returns an HTTP handler which forwards data between | ||
// an incoming and outgoing TCP connection including the original request. | ||
// This handler establishes a new outgoing connection per request. | ||
func newRawProxy(t *url.URL) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
hj, ok := w.(http.Hijacker) | ||
if !ok { | ||
http.Error(w, "not a hijacker", http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
in, _, err := hj.Hijack() | ||
if err != nil { | ||
log.Printf("[ERROR] Hijack error for %s. %s", r.URL, err) | ||
http.Error(w, "hijack error", http.StatusInternalServerError) | ||
return | ||
} | ||
defer in.Close() | ||
|
||
out, err := net.Dial("tcp", t.Host) | ||
if err != nil { | ||
log.Printf("[ERROR] WS error for %s. %s", r.URL, err) | ||
http.Error(w, "error contacting backend server", http.StatusInternalServerError) | ||
return | ||
} | ||
defer out.Close() | ||
|
||
err = r.Write(out) | ||
if err != nil { | ||
log.Printf("[ERROR] Error copying request for %s. %s", r.URL, err) | ||
http.Error(w, "error copying request", http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
errc := make(chan error, 2) | ||
cp := func(dst io.Writer, src io.Reader) { | ||
_, err := io.Copy(dst, src) | ||
errc <- err | ||
} | ||
|
||
go cp(out, in) | ||
go cp(in, out) | ||
err = <-errc | ||
if err != nil && err != io.EOF { | ||
log.Printf("[INFO] WS error for %s. %s", r.URL, err) | ||
} | ||
}) | ||
} |