blob: c7e097a686cc6fa61b9c7fb5ce7519167cc28093 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
import json
type
Message* = object
cmd*: string
args*: string
MessageParsingError* = object of Exception
proc parseMessage*(data: string): Message {.raises: [MessageParsingError, KeyError].} =
var dataJson: JsonNode
try:
dataJson = parseJson(data)
except JsonParsingError:
raise newException(MessageParsingError, "Invalid JSON: " &
getCurrentExceptionMsg())
except:
raise newException(MessageParsingError, "Unknown error: " &
getCurrentExceptionMsg())
if not dataJson.hasKey("cmd"):
raise newException(MessageParsingError, "Cmd field missing")
result.cmd = dataJson["cmd"].getStr()
if result.cmd.len == 0:
raise newException(MessageParsingError, "Cmd field is empty")
if not dataJson.hasKey("args"):
raise newException(MessageParsingError, "Args field missing")
result.args = dataJson["args"].getStr()
if result.args.len == 0:
raise newException(MessageParsingError, "Args field is empty")
proc createMessage*(cmd, args: string): string =
result = $(%{
"cmd": %cmd,
"args": %args
}) & "\c\l"
when isMainModule:
block:
let data = """{"cmd": "status", "args": "verbose"}"""
let parsed = parseMessage(data)
doAssert parsed.cmd == "status"
doAssert parsed.args == "verbose"
# Test failure
block:
try:
let parsed = parseMessage("asdasd")
except MessageParsingError:
doAssert true
except:
doAssert false
|