thttpclient_standalone.nim 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. discard """
  2. cmd: "nim c --threads:on $file"
  3. """
  4. import asynchttpserver, httpclient, asyncdispatch, strutils, net
  5. import std/assertions
  6. block: # bug #16436
  7. proc startServer(): AsyncHttpServer =
  8. result = newAsyncHttpServer()
  9. result.listen(Port(0))
  10. proc processRequest(server: AsyncHttpServer) {.async.} =
  11. proc cb(req: Request) {.async.} =
  12. let headers = { "Content-length": "15"} # Provide invalid content-length
  13. await req.respond(Http200, "Hello World", headers.newHttpHeaders())
  14. await server.acceptRequest(cb)
  15. proc runClient(port: Port) {.async.} =
  16. let c = newAsyncHttpClient(headers = {"Connection": "close"}.newHttpHeaders)
  17. discard await c.getContent("http://127.0.0.1:" & $port)
  18. doAssert false, "should fail earlier"
  19. let server = startServer()
  20. asyncCheck processRequest(server)
  21. let port = server.getPort()
  22. doAssertRaises(ProtocolError):
  23. waitFor runClient(port)
  24. block: # bug #14794 (And test for presence of content-length header when using postContent)
  25. proc startServer(): AsyncHttpServer =
  26. result = newAsyncHttpServer()
  27. result.listen(Port(0))
  28. proc runServer(server: AsyncHttpServer) {.async.} =
  29. proc cb(req: Request) {.async.} =
  30. doAssert(req.body.endsWith(httpNewLine), "Multipart body does not end with a newline.")
  31. # this next line is probably not required because asynchttpserver does not call
  32. # the callback when there is no content-length header. It instead errors with
  33. # Error: unhandled exception: 411 Length Required
  34. # Added for good measure in case the server becomes more permissive.
  35. doAssert(req.headers.hasKey("content-length"), "Content-Length header is not present.")
  36. asyncCheck req.respond(Http200, "OK")
  37. await server.acceptRequest(cb)
  38. proc runClient(port: Port) {.async.} =
  39. let c = newAsyncHttpClient()
  40. let data = newMultipartData()
  41. data.add("file.txt", "This is intended to be an example text file.\r\nThis would be the second line.\r\n")
  42. discard await c.postContent("http://127.0.0.1:" & $port, multipart = data)
  43. c.close()
  44. let server = startServer()
  45. let port = server.getPort()
  46. asyncCheck runServer(server)
  47. waitFor runClient(port)