Skip to content

Commit

Permalink
add getPort to resolve Port(0)
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour committed Mar 28, 2021
1 parent 207bcab commit 4315108
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@
- Added `asyncdispatch.activeDescriptors` that returns the number of currently
active async event handles/file descriptors.

- Added to `asynchttpserver` `getPort` and `getSocket`.

- `--gc:orc` is now 10% faster than previously for common workloads. If
you have trouble with its changed behavior, compile with `-d:nimOldOrc`.

Expand Down
16 changes: 15 additions & 1 deletion lib/pure/asynchttpserver.nim
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,14 @@ runnableExamples("-r:off"):

import asyncnet, asyncdispatch, parseutils, uri, strutils
import httpcore
from nativesockets import getLocalAddr, AF_INET
import std/private/since

export httpcore except parseHeader

since (1, 5, 1):
export Port

const
maxLine = 8*1024

Expand All @@ -70,17 +74,27 @@ type
maxBody: int ## The maximum content-length that will be read for the body.
maxFDs: int

proc getPort*(a: AsyncHttpServer): Port {.since: (1, 5, 1).} =
## Returns the port `a` was bound do to.
## Useful when `listen(Port(0))` was called which assigns a port automatically.
runnableExamples:
let server = newAsyncHttpServer()
server.listen(Port(0))
doAssert server.getPort.uint16 > 0
server.close()
result = getLocalAddr(a.socket.getFd, AF_INET)[1]

func getSocket*(a: AsyncHttpServer): AsyncSocket {.since: (1, 5, 1).} =
## Returns the `AsyncHttpServer`s internal `AsyncSocket` instance.
##
## Useful for identifying what port the AsyncHttpServer is bound to, if it
## was chosen automatically.
runnableExamples:
from std/asyncdispatch import Port
from std/asyncnet import getFd
from std/nativesockets import getLocalAddr, AF_INET
let server = newAsyncHttpServer()
server.listen(Port(0)) # Socket is not bound until this point
# note: a more direct way to get the port is `getPort`.
let port = getLocalAddr(server.getSocket.getFd, AF_INET)[1]
doAssert uint16(port) > 0
server.close()
Expand Down

0 comments on commit 4315108

Please sign in to comment.