thttpclient_standalone.nim 2.1 KB

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