This repository has been archived by the owner on Jan 24, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Add websocket support #201
Open
soellman
wants to merge
2
commits into
bitly:master
Choose a base branch
from
soellman:websocket
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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,138 @@ | ||
package main | ||
|
||
import ( | ||
"io" | ||
"log" | ||
"net/http" | ||
"net/url" | ||
"strings" | ||
"sync" | ||
"time" | ||
|
||
"github.com/gorilla/websocket" | ||
) | ||
|
||
var ( | ||
ConnectionHeaderKey = http.CanonicalHeaderKey("connection") | ||
SetCookieHeaderKey = http.CanonicalHeaderKey("set-cookie") | ||
UpgradeHeaderKey = http.CanonicalHeaderKey("upgrade") | ||
WSKeyHeaderKey = http.CanonicalHeaderKey("sec-websocket-key") | ||
WSProtocolHeaderKey = http.CanonicalHeaderKey("sec-websocket-protocol") | ||
WSVersionHeaderKey = http.CanonicalHeaderKey("sec-websocket-version") | ||
|
||
ConnectionHeaderValue = "Upgrade" | ||
UpgradeHeaderValue = "websocket" | ||
|
||
HandshakeHeaders = []string{ConnectionHeaderKey, UpgradeHeaderKey, WSVersionHeaderKey, WSKeyHeaderKey} | ||
UpgradeHeaders = []string{SetCookieHeaderKey, WSProtocolHeaderKey} | ||
) | ||
|
||
func (u *UpstreamProxy) handleWebsocket(w http.ResponseWriter, r *http.Request) { | ||
|
||
// Copy request headers and remove websocket handshaking headers | ||
// before submitting to the upstream server | ||
upstreamHeader := http.Header{} | ||
for key, _ := range r.Header { | ||
copyHeader(&upstreamHeader, r.Header, key) | ||
} | ||
for _, header := range HandshakeHeaders { | ||
delete(upstreamHeader, header) | ||
} | ||
upstreamHeader.Set("Host", r.Host) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think this also needs |
||
|
||
// Connect upstream | ||
upstreamAddr := u.upstreamWSURL(*r.URL).String() | ||
upstream, upstreamResp, err := websocket.DefaultDialer.Dial(upstreamAddr, upstreamHeader) | ||
if err != nil { | ||
if upstreamResp != nil { | ||
log.Printf("dialing upstream websocket failed with code %d: %v", upstreamResp.StatusCode, err) | ||
} else { | ||
log.Printf("dialing upstream websocket failed: %v", err) | ||
} | ||
http.Error(w, "websocket unavailable", http.StatusServiceUnavailable) | ||
return | ||
} | ||
defer upstream.Close() | ||
|
||
// Pass websocket handshake response headers to the upgrader | ||
upgradeHeader := http.Header{} | ||
copyHeaders(&upgradeHeader, upstreamResp.Header, UpgradeHeaders) | ||
|
||
// Upgrade the client connection without validating the origin | ||
upgrader := websocket.Upgrader{ | ||
CheckOrigin: func(r *http.Request) bool { return true }, | ||
} | ||
client, err := upgrader.Upgrade(w, r, upgradeHeader) | ||
if err != nil { | ||
log.Printf("couldn't upgrade websocket request: %v", err) | ||
http.Error(w, "websocket upgrade failed", http.StatusServiceUnavailable) | ||
return | ||
} | ||
|
||
// Wire both sides together and close when finished | ||
var wg sync.WaitGroup | ||
cp := func(dst, src *websocket.Conn) { | ||
defer wg.Done() | ||
_, err := io.Copy(dst.UnderlyingConn(), src.UnderlyingConn()) | ||
|
||
var closeMessage []byte | ||
if err != nil { | ||
closeMessage = websocket.FormatCloseMessage(websocket.CloseProtocolError, err.Error()) | ||
} else { | ||
closeMessage = websocket.FormatCloseMessage(websocket.CloseNormalClosure, "bye") | ||
} | ||
// Attempt to close the connection properly | ||
dst.WriteControl(websocket.CloseMessage, closeMessage, time.Now().Add(2*time.Second)) | ||
src.WriteControl(websocket.CloseMessage, closeMessage, time.Now().Add(2*time.Second)) | ||
} | ||
wg.Add(2) | ||
go cp(upstream, client) | ||
go cp(client, upstream) | ||
wg.Wait() | ||
} | ||
|
||
// Create a websocket URL from the request URL | ||
func (u *UpstreamProxy) upstreamWSURL(r url.URL) *url.URL { | ||
ws := r | ||
ws.User = r.User | ||
ws.Host = u.upstream.Host | ||
ws.Fragment = "" | ||
switch u.upstream.Scheme { | ||
case "http": | ||
ws.Scheme = "ws" | ||
case "https": | ||
ws.Scheme = "wss" | ||
} | ||
return &ws | ||
} | ||
|
||
func isWebsocketRequest(req *http.Request) bool { | ||
return isHeaderValuePresent(req.Header, UpgradeHeaderKey, UpgradeHeaderValue) && | ||
isHeaderValuePresent(req.Header, ConnectionHeaderKey, ConnectionHeaderValue) | ||
} | ||
|
||
func isHeaderValuePresent(headers http.Header, key string, value string) bool { | ||
for _, header := range headers[key] { | ||
for _, v := range strings.Split(header, ",") { | ||
if strings.EqualFold(value, strings.TrimSpace(v)) { | ||
return true | ||
} | ||
} | ||
} | ||
return false | ||
} | ||
|
||
func copyHeaders(dst *http.Header, src http.Header, headers []string) { | ||
for _, header := range headers { | ||
copyHeader(dst, src, header) | ||
} | ||
} | ||
|
||
// Copy any non-empty and non-blank header values | ||
func copyHeader(dst *http.Header, src http.Header, header string) { | ||
for _, value := range src[header] { | ||
if value != "" { | ||
dst.Add(header, value) | ||
} | ||
} | ||
} |
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,47 @@ | ||
package main | ||
|
||
import ( | ||
"net/http" | ||
"testing" | ||
|
||
"github.com/bmizerany/assert" | ||
) | ||
|
||
func TestCopyHeader(t *testing.T) { | ||
src := http.Header{ | ||
"EmptyValue": []string{""}, | ||
"Nil": []string{}, | ||
"Single": []string{"one"}, | ||
"Multi": []string{"one", "two"}, | ||
} | ||
expected := http.Header{ | ||
"Single": []string{"one"}, | ||
"Multi": []string{"one", "two"}, | ||
} | ||
dst := http.Header{} | ||
for key, _ := range src { | ||
copyHeader(&dst, src, key) | ||
} | ||
assert.Equal(t, expected, dst) | ||
} | ||
|
||
func TestUpgrade(t *testing.T) { | ||
tests := []struct { | ||
upgrade bool | ||
connectionValue string | ||
upgradeValue string | ||
}{ | ||
{true, "Upgrade", "Websocket"}, | ||
{true, "keepalive, Upgrade", "websocket"}, | ||
{false, "", "websocket"}, | ||
{false, "keepalive, Upgrade", ""}, | ||
} | ||
|
||
for _, tt := range tests { | ||
req := new(http.Request) | ||
req.Header = http.Header{} | ||
req.Header.Set(ConnectionHeaderKey, tt.connectionValue) | ||
req.Header.Set(UpgradeHeaderKey, tt.upgradeValue) | ||
assert.Equal(t, tt.upgrade, isWebsocketRequest(req)) | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I needed to add "sec-websocket-extensions" to this list to get it to work. (See https://github.com/gorilla/websocket/blob/a91eba7f97777409bc2c443f5534d41dd20c5720/client.go#L237)
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice find, I also needed this!