Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

HTTP Client

# http_client.nim

{.push gcsafe, raises: [].}

import json_rpc/rpcclient
import ./[rpc_format, http_server]

createRpcSigsFromNim(RpcClient, RpcConv):
  proc hello(input: string): string
  proc bye(input: string): string
  proc `🙂`(input: string): string
  proc empty()
  proc justHello(): string
  proc teaPot()

proc main() {.async.} =
  let srv = startServer()
  defer:
    await srv.stopServer()

  let client = newRpcHttpClient()
  await client.connect("http://" & $srv.localAddress()[0])
  defer:
    await client.close()

  let resp1 = await client.hello("Daisy")
  doAssert resp1 == "Hello Daisy"

  let resp2 = await client.call("hello", %* ["Daisy"], RpcConv)
  doAssert RpcConv.decode(resp2, string) == "Hello Daisy"

  let resp3 = await client.call("hello", %* {"input": "Daisy"}, RpcConv)
  doAssert RpcConv.decode(resp3, string) == "Hello Daisy"

  let resp4 = await client.call("justHello", %* [], RpcConv)
  doAssert RpcConv.decode(resp4, string) == "Hello"

  let resp5 = await client.bye("Daisy")
  doAssert resp5 == "Bye Daisy"

  let resp6 = await client.call("bye", %* {"user-name": "Daisy"}, RpcConv)
  doAssert RpcConv.decode(resp6, string) == "Bye Daisy"

  let resp7 = await client.`🙂`("Daisy")
  doAssert resp7 == "🙂 Daisy"

  let batch = client.prepareBatch()
  batch.hello("Daisy")
  batch.`🙂`("Daisy")
  let batchRes = await batch.send()
  let r = batchRes.tryGet()
  doAssert r[0].error.isNone
  doAssert RpcConv.decode(r[0].result, string) == "Hello Daisy"
  doAssert r[1].error.isNone
  doAssert RpcConv.decode(r[1].result, string) == "🙂 Daisy"

  await client.notify("empty", RequestParamsTx())

  try:
    discard await client.teaPot()
    doAssert false
  except JsonRpcError as err:
    doAssert err.msg == """{"code":418,"message":"I'm a teapot"}"""

when isMainModule:
  waitFor main()
  echo "ok"