Skip to content

Added extra headers #35

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
11 changes: 10 additions & 1 deletion src/ws.nim
Original file line number Diff line number Diff line change
Expand Up @@ -120,10 +120,12 @@ proc newWebSocket*(

proc newWebSocket*(
url: string,
protocols: seq[string] = @[]
protocols: seq[string] = @[],
extraHeaders: seq[(string, string)] = @[],
): Future[WebSocket] {.async.} =
## Creates a new WebSocket connection,
## protocol is optional, "" means no protocol.
## extra headers is optional
var ws = WebSocket()
ws.masked = true
ws.tcpSocket = newAsyncSocket()
Expand Down Expand Up @@ -160,6 +162,13 @@ proc newWebSocket*(
"Sec-WebSocket-Key": secKey,
# "Sec-WebSocket-Extensions": "permessage-deflate; client_max_window_bits"
})

if extraHeaders.len > 0:
# Insert the extra headers
for pairs in extraHeaders:
let (exHeader, exHeaderValue) = pairs
client.headers[exHeader] = exHeaderValue

if protocols.len > 0:
client.headers["Sec-WebSocket-Protocol"] = protocols.join(", ")
var res = await client.get($uri)
Expand Down
24 changes: 24 additions & 0 deletions tests/test_ws_extra_headers.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
include ../src/ws

# Start server
proc cb(req: Request) {.async.} =
var ws = await newWebSocket(req)
if req.headers.hasKey("Authorization") and req.headers["Authorization"] == "Basic Zm9vOmJhcg==":
await ws.send("Welcome")
else:
await ws.send("Bad Credential")
ws.close()

var server = newAsyncHttpServer()
asyncCheck server.serve(Port(9001), cb)

# Send request
let extraHeaders = @[("Authorization", "Basic Zm9vOmJhcg==")] # Base64 foo:bar
let url = "ws://127.0.0.1:9001/ws"
var ws = waitFor newWebSocket(url = url, extraHeaders = extraHeaders)
let packet = waitFor ws.receiveStrPacket()

assert packet == "Welcome"

ws.close()
server.close()
2 changes: 1 addition & 1 deletion ws.nimble
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Package

version = "0.5.0"
version = "0.5.1"
author = "Andre von Houck"
description = "Simple WebSocket library for nim."
license = "MIT"
Expand Down