diff options
| author | Oskari Timperi <oskari.timperi@iki.fi> | 2018-04-23 22:51:29 +0300 |
|---|---|---|
| committer | Oskari Timperi <oskari.timperi@iki.fi> | 2018-04-23 22:51:29 +0300 |
| commit | 8f6f08eaa329162401f8d0e10bb28cdda1e30b2b (patch) | |
| tree | a9741a4d62ccc4e1a599fa1203e0dfb0e1787bd5 | |
| parent | 3d786878ac839e558bde0a096f74638f38adec86 (diff) | |
| download | nimtwirp-8f6f08eaa329162401f8d0e10bb28cdda1e30b2b.tar.gz nimtwirp-8f6f08eaa329162401f8d0e10bb28cdda1e30b2b.zip | |
Add nimtwirp.validateRequest()
Move request validation to a separate proc instead of generating the checks
inline for all handleRequest() procs.
| -rw-r--r-- | nimtwirp/generator.nim | 11 | ||||
| -rw-r--r-- | nimtwirp/nimtwirp.nim | 17 |
2 files changed, 18 insertions, 10 deletions
diff --git a/nimtwirp/generator.nim b/nimtwirp/generator.nim index 167ad17..e3f94b2 100644 --- a/nimtwirp/generator.nim +++ b/nimtwirp/generator.nim @@ -54,16 +54,7 @@ proc new{service.name}*(): {service.name} = new(result) proc handleRequest*(service: {service.name}, req: Request): Future[nimtwirp.Response] {{.async.}} = - if req.reqMethod != HttpPost: - raise newTwirpError(TwirpBadRoute, "only POST accepted") - - if getOrDefault(req.headers, "Content-Type") != "application/protobuf": - raise newTwirpError(TwirpInternal, "invalid Content-Type") - - if not startsWith(req.url.path, {service.name}Prefix): - raise newTwirpError(TwirpBadRoute, "unknown service") - - let methodName = req.url.path[len({service.name}Prefix)..^1] + let (_, methodName) = validateRequest(req, {service.name}Prefix) """ diff --git a/nimtwirp/nimtwirp.nim b/nimtwirp/nimtwirp.nim index 7c30980..f3fa29d 100644 --- a/nimtwirp/nimtwirp.nim +++ b/nimtwirp/nimtwirp.nim @@ -4,6 +4,7 @@ import httpclient import json import macros import strformat +import strutils import errors @@ -116,3 +117,19 @@ proc request*(client: Client, prefix: string, meth: string, body: string): httpc raise newTwirpError(TwirpInternal, "Invalid Content-Type in response") let errorInfo = parseJson(result.body) raise twirpErrorFromJson(errorInfo) + +proc validateRequest*(request: asynchttpserver.Request, prefix: string): tuple[contentType: string, methodName: string] = + if request.reqMethod != HttpPost: + raise newTwirpError(TwirpBadRoute, "only POST accepted") + + result.contentType = getOrDefault(request.headers, "Content-Type") + + if result.contentType != "application/protobuf": + raise newTwirpError(TwirpInternal, + "expected Content-Type to be application/protobuf instead of " & + result.contentType) + + if not startsWith(request.url.path, prefix): + raise newTwirpError(TwirpBadRoute, "unknown service") + + result.methodName = request.url.path[len(prefix)..^1] |
