AnP/Go/Models/RoutesModel.go

92 lines
1.8 KiB
Go

package Models
import (
"AnP/Utils"
"regexp"
"strings"
)
const (
RouteTypeUnknown = iota
RouteTypePath
RouteTypeView
RouteTypeController
)
type RoutesModel struct {
Method string
URL *regexp.Regexp
View string
Path string
Ok bool
I int
Variables []string
Permissions []string
Type int
}
func NewRoutesModel(pattern string) RoutesModel {
var matches Utils.PatternMatch = Utils.Patterns.Match(pattern, Utils.Patterns.RE_ROUTE)
var route RoutesModel = RoutesModel{
Ok: matches.Ok,
}
if matches.Ok {
var pattern string
route.Variables = []string{}
pattern = `(?i)^` + Utils.Patterns.Replace(matches.Groups[3], Utils.Patterns.RE_ROUTES_FORMAT, func(matches Utils.PatternMatch) string {
if matches.Groups[1] != "" {
route.Variables = append(route.Variables, matches.Groups[1])
return `([^\/]+)`
}
return `\` + matches.Groups[2]
})
if matches.Groups[8] != "" {
route.Variables = append(route.Variables, "path")
pattern += `(.*)$`
} else {
pattern += `$`
}
route.Method = strings.ToLower(matches.Groups[2])
route.URL = regexp.MustCompile(pattern)
// 5 - 6 == Controller - Method
route.View = matches.Groups[7]
route.Path = matches.Groups[8]
if matches.Groups[10] != "" {
route.Permissions = strings.Split(matches.Groups[10], ",")
}
if route.Path != "" {
route.Type = RouteTypePath
} else if route.View != "" {
route.Type = RouteTypeView
}
}
return route
}
func (_self RoutesModel) IsSame(route RoutesModel) bool {
return route.Method == _self.Method && route.URL == _self.URL
}
func (_self RoutesModel) GetVariables(matches Utils.PatternMatch) map[string]any {
var url_variables map[string]any = map[string]any{}
for i, key := range _self.Variables {
url_variables[key] = matches.Groups[i+1]
}
return url_variables
}