type Server* = object
port: int
routes: Table[string, Table[string, proc(request: Request) {.cdecl.}]]
allowedMethods: seq[string]
proc newServer*: Server =
result.port = 8080
result.allowedMethods = @["GET", "POST"]
result.routes = initTable[string, Table[string, proc(request: Request) {.cdecl.}]]()
proc addRoute*(self: Server, httpMethod, route: string, handler: proc(request: Request) {.cdecl.}) =
if self.routes.hasKey(httpMethod):
self.routes[httpMethod][route] = handler # Error here before [route]
else:
self.routes[httpMethod] = {route: handler}.toTable
Throws
Error: type mismatch: got <Table[system.string, proc (request: Request){.cdecl.}], string, proc (request: Request){.cdecl.}>
What I need is
{
"GET": {
"/path1": handler1,
"/path2": handler2
},
"POST": {
"/path3": handler3,
"/path4": handler4
}
}
Hi @vbxx3 !
What is the type of httpMethod in the addRoute* method ? You haven't defined it in the method definition.
This compiles:
import tables, asynchttpserver
type Server* = object
port: int
routes: Table[string, Table[string, proc(request: Request) {.cdecl.}]]
allowedMethods: seq[string]
proc newServer*: Server =
result.port = 8080
result.allowedMethods = @["GET", "POST"]
result.routes = initTable[string, Table[string, proc(request: Request) {.cdecl.}]]()
proc addRoute*(self: var Server, httpMethod, route: string, handler: proc(request: Request) {.cdecl.}) =
if self.routes.hasKey(httpMethod):
self.routes[httpMethod][route] = handler # Error here before [route]
else:
self.routes[httpMethod] = {route: handler}.toTable
You might want to look into "jester" though.
import net
import strutils
import tables
import asynchttpserver, asyncdispatch
type Server* = object
port: int
routes: Table[string, Table[string, proc(request: Request) {.cdecl.}]]
allowedMethods: seq[string]
proc newServer*: Server =
result.port = 8080
result.allowedMethods = @["GET", "POST"]
result.routes = initTable[string, Table[string, proc(request: Request) {.cdecl.}]]()
proc addRoute*(self: Server, httpMethod, route: string, handler: proc(request: Request) {.cdecl.}) =
if httpMethod.toUpperAscii() notin self.allowedMethods:
raise newException(Exception, "Method is not allowed")
if route.startsWith('/'):x
raise newException(Exception, "Route must be started with /")
if self.routes.hasKey(httpMethod):
self.routes[httpMethod][route] = handler
else:
self.routes[httpMethod] = {route: handler}.toTable
proc runServer*(self: Server) =
echo "======== Running on http://0.0.0.0:" & $self.port & " ========"
This way it doesn't:) I like aiohttp framework style, but Jester is nice too.