mirror of
https://github.com/status-im/nim-json-rpc.git
synced 2025-02-24 10:18:15 +00:00
Json extraction for http server read
This commit is contained in:
parent
d36da9d14c
commit
f8e178e5b3
@ -1,18 +1,31 @@
|
||||
import rpcserver, rpcclient, tables, chronicles, strformat, strutils
|
||||
export rpcserver, rpcclient
|
||||
|
||||
proc extractJsonStr(msgSource: string, value: string): string =
|
||||
result = ""
|
||||
let p1 = find(value, '{')
|
||||
if p1 > -1:
|
||||
let p2 = rFind(value, '}')
|
||||
if p2 == -1:
|
||||
info "Cannot find json end brace", source = msgSource, msg = value
|
||||
else:
|
||||
result = value[p1 .. p2]
|
||||
debug "Extracted json", source = msgSource, json = result
|
||||
else:
|
||||
info "Cannot find json start brace", source = msgSource, msg = value
|
||||
|
||||
type
|
||||
RpcHttpServer* = RpcServer[StreamServer]
|
||||
|
||||
defineRpcServerTransport(httpProcessClient):
|
||||
write:
|
||||
const contentType = "Content-Type: application/json-rpc"
|
||||
let msg = &"Host: {$client.localAddress} {contentType} Content-Length: {$value.len} {value}"
|
||||
debug "Http write", msg = msg
|
||||
client.write(msg)
|
||||
let msg = &"Host: {$transport.localAddress} {contentType} Content-Length: {$value.len} {value}"
|
||||
debug "HTTP server: write", msg = msg
|
||||
transport.write(msg)
|
||||
afterRead:
|
||||
# TODO: read: remove http to allow json validation
|
||||
debug "Http read", msg = value
|
||||
debug "HTTP server: read", msg = value
|
||||
value = "HTTP Server".extractJsonStr(value)
|
||||
|
||||
proc newRpcHttpServer*(addresses: openarray[TransportAddress]): RpcHttpServer =
|
||||
## Create new server and assign it to addresses ``addresses``.
|
||||
@ -31,21 +44,16 @@ proc newRpcHttpServer*(address = "localhost", port: Port = Port(8545)): RpcHttpS
|
||||
type RpcHttpClient* = RpcClient[StreamTransport, TransportAddress]
|
||||
|
||||
defineRpcClientTransport(StreamTransport, TransportAddress, "http"):
|
||||
read:
|
||||
client.transp.readLine()
|
||||
write:
|
||||
const contentType = "Content-Type: application/json-rpc"
|
||||
value = &"Host: {$client.transp.localAddress} {contentType} Content-Length: {$value.len} {value}"
|
||||
debug "HTTP client: write", msg = value
|
||||
client.transp.write(value)
|
||||
afterRead:
|
||||
# Strip out http header
|
||||
# TODO: Performance
|
||||
let p1 = find(value, '{')
|
||||
if p1 > -1:
|
||||
let p2 = rFind(value, '}')
|
||||
if p2 == -1:
|
||||
info "Cannot find json end brace", msg = value
|
||||
else:
|
||||
value = value[p1 .. p2]
|
||||
debug "Extracted json", json = value
|
||||
else:
|
||||
info "Cannot find json start brace", msg = value
|
||||
debug "HTTP client: read", msg = value
|
||||
value = "HTTP Client".extractJsonStr(value)
|
||||
|
||||
proc newRpcHttpClient*(): RpcHttpClient =
|
||||
result = newRpcClient[StreamTransport, TransportAddress]()
|
||||
|
Loading…
x
Reference in New Issue
Block a user