Basic route parser in place
This commit is contained in:
parent
a70912c465
commit
825599b8c8
|
@ -0,0 +1,94 @@
|
|||
// Copyright (c) 2022 David Satime Wallin. All rights reserved.
|
||||
// Use of this source code is governed by an MIT license
|
||||
// that can be found in the LICENSE file.
|
||||
module router
|
||||
|
||||
import os
|
||||
|
||||
const (
|
||||
config_file = 'conf/routes'
|
||||
)
|
||||
|
||||
pub struct Route {
|
||||
method string
|
||||
path string
|
||||
controller string
|
||||
function string
|
||||
}
|
||||
|
||||
pub fn run_parse() []Route {
|
||||
if !os.exists(config_file) {
|
||||
eprintln('$config_file not found')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
routes := get_routes_from_config()
|
||||
for route in routes {
|
||||
if !route_exist(route) {
|
||||
eprintln('route ${route.controller}/${route.function} not found')
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
return routes
|
||||
}
|
||||
|
||||
fn route_exist(route Route) bool {
|
||||
file := 'Controllers/${route.controller}.v'
|
||||
if !os.exists(file) {
|
||||
eprintln('could not find $file')
|
||||
|
||||
return false
|
||||
}
|
||||
file_content := os.read_file(file) or {
|
||||
eprintln('could not read $file')
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
if !file_content.contains('fn ${route.function}()') {
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
fn get_routes_from_config() []Route {
|
||||
mut routes := []Route{}
|
||||
|
||||
lines := os.read_lines(config_file) or {
|
||||
eprintln('could not read from $config_file')
|
||||
exit(1)
|
||||
}
|
||||
|
||||
for line in lines {
|
||||
if line.starts_with('#') { // avoid comment-lines
|
||||
continue
|
||||
}
|
||||
cols := clean_route_array(line.all_before('#').split(' '))
|
||||
if cols.len != 4 {
|
||||
eprintln('$config_file looks wrong: $cols')
|
||||
exit(1)
|
||||
}
|
||||
routes << Route{
|
||||
method: cols[0],
|
||||
path: cols[1],
|
||||
controller: cols[2],
|
||||
function: cols[3]
|
||||
}
|
||||
}
|
||||
|
||||
return routes
|
||||
}
|
||||
|
||||
fn clean_route_array(cols []string) []string {
|
||||
mut array_copy := []string{}
|
||||
for col in cols {
|
||||
if col != '' {
|
||||
array_copy << col
|
||||
}
|
||||
}
|
||||
|
||||
return array_copy
|
||||
}
|
12
veb.v
12
veb.v
|
@ -0,0 +1,12 @@
|
|||
// Copyright (c) 2022 David Satime Wallin. All rights reserved.
|
||||
// Use of this source code is governed by an MIT license
|
||||
// that can be found in the LICENSE file.
|
||||
module main
|
||||
|
||||
import router
|
||||
|
||||
fn main() {
|
||||
println("hej")
|
||||
routes := router.run_parse()
|
||||
println("routes: $routes")
|
||||
}
|
Loading…
Reference in New Issue