veb/modules/router/router.v

94 lines
1.6 KiB
V

// 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 {
ok, err := route_exist(route)
if !ok {
eprintln(err)
exit(1)
}
}
return routes
}
fn route_exist(route Route) (bool,string) {
file := 'Controllers/${route.controller}.v'
if !os.exists(file) {
return false, 'could not find $file'
}
file_content := os.read_file(file) or {
return false, 'could not read $file'
}
if !file_content.contains('fn ${route.function}()') {
return false, '${route.function} not properly defined'
}
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
}