107 lines
2.3 KiB
Go
107 lines
2.3 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
|
|
Options map[string]any
|
|
}
|
|
|
|
func NewRoutesModel(pattern string, options map[string]map[string]any) RoutesModel {
|
|
|
|
var matches Utils.PatternMatch = Utils.Patterns.Match(pattern, Utils.Patterns.RE_ROUTE)
|
|
var route RoutesModel = RoutesModel{
|
|
Ok: matches.Ok,
|
|
Options: nil,
|
|
}
|
|
|
|
if matches.Ok {
|
|
// RE_ROUTE: all, method?, route, (method, controller | view | path), permissions?, options?
|
|
|
|
var pattern string
|
|
|
|
route.Variables = []string{}
|
|
pattern = `(?i)^` + Utils.Patterns.Replace(matches.Groups[2], 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[6] != "" {
|
|
route.Variables = append(route.Variables, "path")
|
|
pattern += `(.*)$`
|
|
} else {
|
|
pattern += `$`
|
|
}
|
|
|
|
route.Method = strings.ToLower(matches.Groups[1])
|
|
route.URL = regexp.MustCompile(pattern)
|
|
// 3 - 4 == Controller - Method
|
|
route.View = matches.Groups[5]
|
|
route.Path = matches.Groups[6]
|
|
|
|
if matches.Groups[7] != "" {
|
|
route.Permissions = strings.Split(matches.Groups[7], ",")
|
|
}
|
|
if matches.Groups[8] != "" {
|
|
route.Options = map[string]any{}
|
|
for _, key := range strings.Split(matches.Groups[8], ",") {
|
|
if headers, exists := options[key]; exists {
|
|
for key, value := range headers {
|
|
if _, exists := route.Options[key]; !exists {
|
|
route.Options[key] = value
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|