tasynchttpserver_transferencoding.nim 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. discard """
  2. matrix: "--mm:arc; --mm:arc -d:danger; --mm:refc"
  3. disabled: "freebsd"
  4. """
  5. import httpclient, asynchttpserver, asyncdispatch, asyncfutures
  6. import net
  7. import std/asyncnet
  8. import std/nativesockets
  9. import std/assertions
  10. const postBegin = """
  11. POST / HTTP/1.1
  12. Transfer-Encoding:chunked
  13. """
  14. template genTest(input, expected: string) =
  15. proc handler(request: Request, future: Future[bool]) {.async, gcsafe.} =
  16. doAssert(request.body == expected)
  17. doAssert(request.headers.hasKey("Transfer-Encoding"))
  18. doAssert(not request.headers.hasKey("Content-Length"))
  19. future.complete(true)
  20. await request.respond(Http200, "Good")
  21. proc sendData(data: string, port: Port) {.async.} =
  22. var socket = newSocket()
  23. defer: socket.close()
  24. socket.connect("127.0.0.1", port)
  25. socket.send(data)
  26. proc runTest(): Future[bool] {.async.} =
  27. var handlerFuture = newFuture[bool]("runTest")
  28. let data = postBegin & input
  29. let server = newAsyncHttpServer()
  30. server.listen(Port(0))
  31. proc wrapper(request: Request): Future[void] {.gcsafe, closure.} =
  32. handler(request, handlerFuture)
  33. asyncCheck sendData(data, server.getPort)
  34. asyncCheck server.acceptRequest(wrapper)
  35. doAssert await handlerFuture
  36. server.close()
  37. return true
  38. doAssert waitFor runTest()
  39. block:
  40. const expected = "hello=world"
  41. const input = ("b\r\n" &
  42. "hello=world\r\n" &
  43. "0\r\n" &
  44. "\r\n")
  45. genTest(input, expected)
  46. block:
  47. const expected = "hello encoding"
  48. const input = ("e\r\n" &
  49. "hello encoding\r\n" &
  50. "0\r\n" &
  51. "\r\n")
  52. genTest(input, expected)
  53. block:
  54. # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
  55. const expected = "MozillaDeveloperNetwork"
  56. const input = ("7\r\n" &
  57. "Mozilla\r\n" &
  58. "9\r\n" &
  59. "Developer\r\n" &
  60. "7\r\n" &
  61. "Network\r\n" &
  62. "0\r\n" &
  63. "\r\n")
  64. genTest(input, expected)
  65. block:
  66. # https://en.wikipedia.org/wiki/Chunked_transfer_encoding#Example
  67. const expected = "Wikipedia in \r\n\r\nchunks."
  68. const input = ("4\r\n" &
  69. "Wiki\r\n" &
  70. "6\r\n" &
  71. "pedia \r\n" &
  72. "E\r\n" &
  73. "in \r\n" &
  74. "\r\n" &
  75. "chunks.\r\n" &
  76. "0\r\n" &
  77. "\r\n")
  78. genTest(input, expected)