So, I'm trying to build a small routing library for asynchttpserver. It's kind 
of just for learning at the moment, but it could turn into something bigger(who 
knows?). I've got it working somewhat the way I want it to but I'm running into 
a little issue:

In the following code on line #82(declaration of 'cb' proc) nimsuggest is 
throwing the error: "template/generic instantiation from here". I'm not 
actually entirely sure if this is a real error as my code compiles and seems to 
work properly. I used the debugger and didn't notice anything strange there 
either.

Even though my code is working properly, I want to make sure I don't have a 
lingering bug waiting to pounce.

Also, any general improvement suggestions are very welcome.
    
    
    import asyncdispatch, asynchttpserver, strutils
    
    
    let server = newAsyncHttpServer()
    
    
    proc notFoundHandler(req: Request) {.async.} =
        await req.respond(Http404, "404 Not Found")
    
    
    type
        Router = ref object of RootObj
            routes: seq[Route]
        Route = ref object of RootObj
            path: string
            get: proc (req: Request): Future[void]
            post: proc (req: Request): Future[void]
            put: proc (req: Request): Future[void]
            delete: proc (req: Request): Future[void]
    
    
    proc newRouter(): Router =
        result = Router(
            routes: @[]
        )
    
    
    proc newRoute(
        path: string,
        get, post, put, delete: proc=notFoundHandler
    ): Route =
        result = Route(
            path: path,
            get: get,
            post: post,
            put: put,
            delete: delete
        )
    
    
    proc register(router: Router, routes: varargs[Route]) =
        for route in items(routes):
            router.routes.add(route)
    
    
    proc route(router: Router, req: Request) {.async.} =
        for route in router.routes:
            if route.path == req.url.path:
                case req.reqMethod:
                    of HttpGet:
                        await route.get(req)
                    else: continue
        await notFoundHandler(req)
    
    
    let router = newRouter()
    
    
    proc indexHandler(req: Request) {.async.} =
        await req.respond(Http200, "This is the home page.")
    
    
    proc helloWorldHandler(req: Request) {.async.} =
        await req.respond(Http200, "Hello, world!")
    
    
    let index = newRoute(
        path="/",
        get=indexHandler
    )
    
    
    let helloWorld = newRoute(
        path="/hello/",
        get=helloWorldHandler
    )
    
    
    router.register(index, helloWorld)
    
    
    proc cb(req: Request) {.async.} =
        await router.route(req)
    
    
    waitFor server.serve(Port(8000), cb)
    
    

Reply via email to