Skip to content

Commit

Permalink
use getPort in examples + tests
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour committed Mar 28, 2021
1 parent ae18a49 commit 2bde084
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 8 deletions.
10 changes: 5 additions & 5 deletions lib/pure/asynchttpserver.nim
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,20 @@
## instead of allowing users to connect directly to this server.

runnableExamples("-r:off"):
# This example will create an HTTP server on port 8080. The server will
# respond to all requests with a `200 OK` response code and "Hello World"
# This example will create an HTTP server on an automatically chosen port.
# It will respond to all requests with a `200 OK` response code and "Hello World"
# as the response body.
import std/asyncdispatch
proc main {.async.} =
const port = 8080
var server = newAsyncHttpServer()
proc cb(req: Request) {.async.} =
echo (req.reqMethod, req.url, req.headers)
let headers = {"Content-type": "text/plain; charset=utf-8"}
await req.respond(Http200, "Hello World", headers.newHttpHeaders())

echo "test this with: curl localhost:" & $port & "/"
server.listen(Port(port))
server.listen(Port(0)) # or Port(8080) to hardcode the standard HTTP port.
let port = server.getPort
echo "test this with: curl localhost:" & $port.uint16 & "/"
while true:
if server.shouldAcceptRequest():
await server.acceptRequest(cb)
Expand Down
3 changes: 2 additions & 1 deletion testament/lib/stdtest/netutils.nim
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import std/[nativesockets, asyncdispatch, os]

proc bindAvailablePort*(handle: SocketHandle, port = Port(0)): Port =
## See also `asynchttpserver.getPort`.
block:
var name: Sockaddr_in
name.sin_family = typeof(name.sin_family)(toInt(AF_INET))
name.sin_port = htons(uint16(port))
name.sin_addr.s_addr = htonl(INADDR_ANY)
if bindAddr(handle, cast[ptr SockAddr](addr(name)),
sizeof(name).Socklen) < 0'i32:
raiseOSError(osLastError())
raiseOSError(osLastError(), $port)
result = getLocalAddr(handle, AF_INET)[1]
3 changes: 1 addition & 2 deletions tests/stdlib/tasynchttpserver_transferencoding.nim
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,9 @@ template genTest(input, expected) =

let server = newAsyncHttpServer()
waitFor runSleepLoop(server)
let port = getLocalAddr(server.getSocket.getFd, AF_INET)[1]
let data = postBegin & input
var socket = newSocket()
socket.connect("127.0.0.1", port)
socket.connect("127.0.0.1", server.getPort)
socket.send(data)
waitFor sleepAsync(10)
socket.close()
Expand Down

0 comments on commit 2bde084

Please sign in to comment.