ws/internal/uri/parser/public.go

115 lines
2.0 KiB
Go
Raw Normal View History

package parser
import (
"fmt"
"strings"
)
// Build builds an URI scheme from a pattern string
func Build(s string) (*Scheme, error){
/* (1) Manage '/' at the start */
if len(s) < 1 || s[0] != '/' {
return nil, fmt.Errorf("URI must begin with '/'")
}
/* (2) Split by '/' */
parts := strings.Split(s, "/")
/* (3) Max exceeded */
if len(parts)-2 > maxMatch {
for i, p := range parts {
fmt.Printf("%d: '%s'\n", i, p);
}
return nil, fmt.Errorf("URI must not exceed %d slash-separated components, got %d", maxMatch, len(parts))
}
/* (4) Build for each part */
sch, err := buildScheme(parts)
if err != nil {
return nil, err
}
/* (5) Optimise structure */
opti, err := sch.optimise()
if err != nil {
return nil, err
}
return &opti, nil
}
// Match returns if the given URI is matched by the scheme
func (s Scheme) Match(str string) bool {
/* (1) Nothing -> match all */
if len(s) == 0 { return true }
/* (2) Check for string match */
clearURI, match := s.matchString(str)
if !match {
return false
}
/* (3) Check for non-string match (wildcards) */
match = s.matchWildcards(clearURI)
if !match {
return false
}
return true
}
// GetMatch returns the indexed match (excluding string matchers)
func (s Scheme) GetMatch(n uint8) ([]string, error) {
/* (1) Index out of range */
if n > uint8(len(s)) {
return nil, fmt.Errorf("Index out of range")
}
/* (2) Iterate to find index (exclude strings) */
ni := -1
for _, m := range s {
// ignore strings
if len(m.pat) > 0 { continue }
// increment match counter : ni
ni++
// if expected index -> return matches
if uint8(ni) == n {
return m.buf, nil
}
}
/* (3) If nothing found -> return empty set */
return nil, fmt.Errorf("Index out of range (max: %d)", ni)
}
// GetAllMatch returns all the indexed match (excluding string matchers)
func (s Scheme) GetAllMatch() [][]string {
match := make([][]string, 0, len(s))
for _, m := range s {
// ignore strings
if len(m.pat) > 0 { continue }
match = append(match, m.buf)
}
return match
}