[refactor] web server routing system (#270)

* [refactor] web server routing system

* regex literal

* Docs
This commit is contained in:
Brahim Hadriche authored and GitHub committed 2024-01-15 19:25:13 -05:00
1 parent a710a23444
commit 7e5b2246fa
25 files changed
+820 -656

No files matched your search

@@ -2,48 +2,36 @@ namespace Http
class HttpRouter
' [{
' method: "GET"
' path: "/example"
' router: router as HttpRouter
' func: func as string
' }]
private routes
function new()
m.routes = []
end function
function Get(path as string, handler as function)
m.routes.push({ method: "GET", path: path, handler: handler })
end function
function Head(path as string, handler as function)
m.routes.push({ method: "HEAD", path: path, handler: handler })
end function
function Post(path as string, handler as function)
m.routes.push({ method: "POST", path: path, handler: handler })
end function
function Put(path as string, handler as function)
m.routes.push({ method: "PUT", path: path, handler: handler })
end function
function Delete(path as string, handler as function)
m.routes.push({ method: "DELETE", path: path, handler: handler })
end function
function All(path as string, handler as function)
m.routes.push({ method: "*", path: path, handler: handler })
end function
private function OnRequest(request as object, response as HttpResponse, connection as HttpConnection) as boolean
for each route in m.routes
if m.RouteMatchesRequest(route, request)
if route.handler({
router: m
request: request
response: response
connection: connection
server: response.server
}) = true
try
if route.router[route.func]({
request: request
response: response
connection: connection
server: response.server
}) = true
return true
end if
catch error
formattedError = ErrorUtils.Format(error)
LogError(formattedError)
response.Default(500, formattedError)
return true
end if
end try
end if
end for
return false
@@ -11,24 +11,24 @@ namespace Http
m.origin = origin
m.headers = headers
m.methods = methods
m.All("*", function(context as object) as boolean
router = context.router
request = context.request
response = context.response
response.headers["Access-Control-Allow-Origin"] = router.origin
response.headers["Access-Control-Allow-Headers"] = router.headers
response.headers["Access-Control-Allow-Methods"] = router.methods
if request.method = "OPTIONS"
response.header_only = true
response.http_code = 200
return true
end if
return false
end function)
end function
@all("*")
function AddAccessControlHeaders(context as object) as boolean
request = context.request
response = context.response
response.headers["Access-Control-Allow-Origin"] = m.origin
response.headers["Access-Control-Allow-Headers"] = m.headers
response.headers["Access-Control-Allow-Methods"] = m.methods
if request.method = "OPTIONS"
response.header_only = true
response.http_code = 200
return true
end if
return false
end function
end class
end namespace
@@ -11,21 +11,21 @@ namespace Http
super()
m.etags = etags
end function
m.Get("*", function(context as object) as boolean
router = context.router
request = context.request
response = context.response
if response.http_code <> 200
return false
end if
router.etags.AddEtagFromBody(request, response)
router.etags.ClearContentIfNoneMatch(request, response)
@get("*")
function HandleEtag(context as object) as boolean
request = context.request
response = context.response
if response.http_code <> 200
return false
end function)
end if
m.etags.AddEtagFromBody(request, response)
m.etags.ClearContentIfNoneMatch(request, response)
return false
end function
end class
@@ -4,24 +4,24 @@ namespace Http
function new()
super()
m.All("*", function(context as object) as boolean
request = context.request
response = context.response
method = request.method
uri = request.uri
if method = ""
response.Default(400, "You sent a request that the server couldn't understand.")
else
response.Default(404, `Cannot ${method} ${uri}`)
end if
return true
end function)
end function
@all("*")
function HandleDefault(context as object) as boolean
request = context.request
response = context.response
method = request.method
uri = request.uri
if method = ""
response.Default(400, "You sent a request that the server couldn't understand.")
else
response.Default(404, `Cannot ${method} ${uri}`)
end if
return true
end function
end class
end namespace
@@ -30,98 +30,98 @@ namespace Http
m.fsCheck = ValidBool(options.fsCheck)
' staticFiles: if true, Etag tags will be cached to skip reading the file entirely.
m.staticFiles = ValidBool(options.staticFiles)
m.Get("*", function(context as object) as boolean
router = context.router
request = context.request
response = context.response
server = context.server
if not request.route.StartsWith(router.route)
return false
end if
path_in_route = request.route.Mid(router.route.Len())
decoded_path = path_in_route.DecodeUri()
full_path = StringUtils.PathJoin(router.root, decoded_path)
if router.staticFiles
' Although we have an Etag middleware, having a check here allows us to
' skip reading the file entirely if the Etag matches.
if router.etags.AddFileEtagFromCache(request, response, full_path)
if router.etags.ClearContentIfNoneMatch(request, response)
return true
end if
end if
end if
if not router.fsCheck
' libpkg:/ does not work with roFilesystem...
buffer = createObject("roByteArray")
if buffer.ReadFile(full_path) and buffer.count() > 0
mimetype = server.utils.MimeType(decoded_path)
response.SetBodyDataBuffer(buffer)
response.ContentType(mimetype)
response.http_code = 200
if router.staticFiles
router.etags.AddEtagFromBody(request, response, full_path)
end if
return true
end if
end if
path = CreateObject("roPath", full_path)
fs = CreateObject("roFilesystem")
if not path.isValid()
' Skip, let next middleware handle it
return false
else if not fs.exists(path)
' Skip, let next middleware handle it
return false
end if
stat = fs.stat(path)
if stat = invalid
response.Default(500, "fstat() failed.")
return true
end if
if stat.type = "directory"
if not router.showDirectories
response.Default(403, "Forbidden")
return true
end if
response.ContentType("text/html")
router.GenerateDirectoryListing(path, router, request, response)
if router.staticFiles
router.etags.AddEtagFromBody(request, response, full_path)
end if
return true
else if stat.type = "file"
mimetype = server.utils.MimeType(decoded_path)
response.ContentType(mimetype)
response.SetBodyDataFile(path)
response.http_code = 200
LogInfo("uri:", request.uri, "target:", path, "content-type:", mimetype, "content-length", stat.size)
if router.staticFiles
router.etags.AddEtagFromBody(request, response, full_path)
end if
return true
else
response.Default(403, "Not a regular file.")
return true
end if
end function)
end function
function GenerateDirectoryListing(path as object, router as object, request as HttpRequest, response as HttpResponse) as boolean
@get("*")
function GetFileOrFolder(context as object) as boolean
request = context.request
response = context.response
server = context.server
if not request.route.StartsWith(m.route)
return false
end if
path_in_route = request.route.Mid(m.route.Len())
decoded_path = path_in_route.DecodeUri()
full_path = StringUtils.PathJoin(m.root, decoded_path)
if m.staticFiles
' Although we have an Etag middleware, having a check here allows us to
' skip reading the file entirely if the Etag matches.
if m.etags.AddFileEtagFromCache(request, response, full_path)
if m.etags.ClearContentIfNoneMatch(request, response)
return true
end if
end if
end if
if not m.fsCheck
' libpkg:/ does not work with roFilesystem...
buffer = createObject("roByteArray")
if buffer.ReadFile(full_path) and buffer.count() > 0
mimetype = server.utils.MimeType(decoded_path)
response.SetBodyDataBuffer(buffer)
response.ContentType(mimetype)
response.http_code = 200
if m.staticFiles
m.etags.AddEtagFromBody(request, response, full_path)
end if
return true
end if
end if
path = CreateObject("roPath", full_path)
fs = CreateObject("roFilesystem")
if not path.isValid()
' Skip, let next middleware handle it
return false
else if not fs.exists(path)
' Skip, let next middleware handle it
return false
end if
stat = fs.stat(path)
if stat = invalid
response.Default(500, "fstat() failed.")
return true
end if
if stat.type = "directory"
if not m.showDirectories
response.Default(403, "Forbidden")
return true
end if
response.ContentType("text/html")
m.GenerateDirectoryListing(path, request, response)
if m.staticFiles
m.etags.AddEtagFromBody(request, response, full_path)
end if
return true
else if stat.type = "file"
mimetype = server.utils.MimeType(decoded_path)
response.ContentType(mimetype)
response.SetBodyDataFile(path)
response.http_code = 200
LogInfo("uri:", request.uri, "target:", path, "content-type:", mimetype, "content-length", stat.size)
if m.staticFiles
m.etags.AddEtagFromBody(request, response, full_path)
end if
return true
else
response.Default(403, "Not a regular file.")
return true
end if
end function
function GenerateDirectoryListing(path as object, request as HttpRequest, response as HttpResponse) as boolean
fs = CreateObject("roFilesystem")
dirList = fs.GetDirectoryListing(path)
if dirList = invalid
response.default(500, "Couldn't list directory")
response.Default(500, "Couldn't list directory")
return false
end if
@@ -151,7 +151,7 @@ namespace Http
uriDir = uriDir + "/"
end if
routeDir = router.route
routeDir = m.route
if routeDir.len() > 0 and routeDir.right(1) <> "/"
routeDir = routeDir + "/"
end if
@@ -162,7 +162,7 @@ namespace Http
end if
for each item in dirList
if router.showHidden or item.left(1) <> "."
if m.showHidden or item.left(1) <> "."
indicator = invalid
stat = fs.stat(dir + item)
if stat <> invalid
@@ -8,42 +8,43 @@ namespace Http
function new()
super()
end function
m.Get("*", function(context as object) as boolean
request = context.request
response = context.response
connection = context.connection
@get("*")
function HandleWebSocketHeaders(context as object) as boolean
request = context.request
response = context.response
connection = context.connection
if LCase(ValidString(request.headers["Connection"])) <> "upgrade"
return false
end if
if LCase(ValidString(request.headers["Connection"])) <> "upgrade"
return false
end if
if LCase(ValidString(request.headers["Upgrade"])) <> "websocket"
return false
end if
if LCase(ValidString(request.headers["Upgrade"])) <> "websocket"
return false
end if
webSocketKey = request.headers["Sec-WebSocket-Key"]
if webSocketKey = invalid
return false
end if
webSocketKey = request.headers["Sec-WebSocket-Key"]
if webSocketKey = invalid
return false
end if
sha1Hash = CryptoUtils.GetSha1(webSocketKey + Http.WEB_SOCKET_MAGIC_STRING)
buffer = CreateObject("roByteArray")
buffer.FromHexString(sha1Hash)
webSocketAccept = StringUtils.ToBase64(buffer.ToAsciiString())
sha1Hash = CryptoUtils.GetSha1(webSocketKey + Http.WEB_SOCKET_MAGIC_STRING)
buffer = CreateObject("roByteArray")
buffer.FromHexString(sha1Hash)
webSocketAccept = StringUtils.ToBase64(buffer.ToAsciiString())
response.http_code = 101
response.headers["Connection"] = "Upgrade"
response.headers["Upgrade"] = "websocket"
response.headers["Sec-WebSocket-Accept"] = webSocketAccept
response.header_only = true
response.http_code = 101
response.headers["Connection"] = "Upgrade"
response.headers["Upgrade"] = "websocket"
response.headers["Sec-WebSocket-Accept"] = webSocketAccept
response.header_only = true
' We want this connection to be upgraded to a WebSocket connection
' The connection will stop being handled by the HTTP server and will be handled by the WebSocket server
connection.ws_upgrade = true
' We want this connection to be upgraded to a WebSocket connection
' The connection will stop being handled by the HTTP server and will be handled by the WebSocket server
connection.ws_upgrade = true
return true
end function)
return true
end function
end class