all repos — wsabi @ 7101712b5ca29826d943b141badf7bd59742e76d

websocket proxy that sends stats to statsd

Clean up responses
Anirudh Oppiliappan x@icyphox.sh
Fri, 24 Jul 2020 16:31:55 +0530
commit

7101712b5ca29826d943b141badf7bd59742e76d

parent

be429cef8aedb13e850e535a31cc369a59395494

2 files changed, 20 insertions(+), 25 deletions(-)

jump to
M src/wsabi.nimsrc/wsabi.nim

@@ -4,7 +4,7 @@ asyncdispatch,

asynchttpserver, strformat, asyncnet, - wsabipkg/args, + wsabipkg/[args,httputils], httpclient, strutils, json,

@@ -81,10 +81,7 @@ echo await ws.receiveStrPacket()

ws.close() let r = %*{"status": "OK"} - await req.respond( - Http200, $r, - newHttpHeaders([("Content-Type", "application/json")]) - ) + await req.makeResponse(Http200, $r) if hc.uri in ["http", "https"]: let hostStr = &"{hc.uri}://{hc.host}:{hc.port}/"

@@ -93,17 +90,11 @@ var tmpClient = newAsyncHttpClient()

echo await tmpClient.getContent(hostStr) let r = %*{"status": "OK"} - await req.respond( - Http200, $r, - newHttpHeaders([("Content-Type", "application/json")]) - ) + await req.makeResponse(Http200, $r) else: let r = %*{"status": "error", "msg": &"unknown URI {hc.uri}"} - await req.respond( - Http400, $r, - newHttpHeaders([("Content-Type", "application/json")]) - ) + await req.makeResponse(Http400, $r) except OSError as e: echo "unable to reach specified host:port pair"

@@ -111,22 +102,16 @@ let r = %*{

"status": "error", "msg": e.msg } - await req.respond( - Http400, $r, - newHttpHeaders([("Content-Type", "application/json")]) - ) + await req.makeResponse(Http400, $r) + except KeyError as e: let r = %*{"status": "error", "msg": e.msg} - await req.respond( - Http400, $r, - newHttpHeaders([("Content-Type", "application/json")]) - ) + await req.makeResponse(Http400, $r) + except WebSocketError as e: let r = %*{"status": "error", "msg": e.msg} - await req.respond( - Http500, $r, - newHttpHeaders([("Content-Type", "application/json")]) - ) + await req.makeResponse(Http500, $r) + when isMainModule:
A src/wsabipkg/httputils.nim

@@ -0,0 +1,10 @@

+import asynchttpserver, asyncdispatch + +proc makeResponse*( + req: Request, code: HttpCode, content: string +) {.async.} = + await req.respond( + code, content, + newHttpHeaders([("Content-Type", "application/json")]) + ) +