Skip to content

Commit

Permalink
path parser
Browse files Browse the repository at this point in the history
  • Loading branch information
cccaaannn committed Jul 27, 2024
1 parent 023a72c commit 2e76f4d
Show file tree
Hide file tree
Showing 2 changed files with 110 additions and 0 deletions.
85 changes: 85 additions & 0 deletions url/path.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package url

import "strings"

type segmentType string

const (
static segmentType = "static"
param segmentType = "param"
wildcard segmentType = "wildcard"
)

type segment struct {
value string
segmentType segmentType
}

type Path struct {
pattern string
segments []segment
}

func parsePathSegments(pattern string) []segment {
segments := make([]segment, 0)
parts := strings.Split(pattern, "/")
for _, part := range parts {
segmentType := static
if strings.HasPrefix(part, ":") {
segmentType = param
part = part[1:]
}
if part == "*" {
segmentType = wildcard
}
segments = append(segments, segment{value: part, segmentType: segmentType})
}
return segments
}

func (path Path) hasWildcard() bool {
hasWildcard := false
for _, segment := range path.segments {
if segment.segmentType == wildcard {
hasWildcard = true
break
}
}
return hasWildcard
}

func CreatePath(pattern string) Path {
segments := parsePathSegments(pattern)
return Path{pattern: pattern, segments: segments}
}

func (path Path) Match(text string) (map[string]string, bool) {
textSegments := strings.Split(text, "/")
params := make(map[string]string)
hasWildcard := path.hasWildcard()

if !hasWildcard {
if len(path.segments) != len(textSegments) {
return nil, false
}
} else {
if len(path.segments) > len(textSegments) {
return nil, false
}
}

for i, segment := range path.segments {
textSegment := textSegments[i]
if segment.segmentType == param {
params[segment.value] = textSegment
continue
}
if segment.segmentType == static && segment.value != textSegment {
return nil, false
}
if segment.segmentType == wildcard {
return params, true
}
}
return params, true
}
25 changes: 25 additions & 0 deletions url/query.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package url

import "strings"

func ParseQuery(query string) map[string]string {
params := make(map[string]string)
parts := strings.Split(query, "&")
for _, part := range parts {
split := strings.Split(part, "=")
if len(split) == 2 {
params[split[0]] = split[1]
} else {
params[split[0]] = ""
}
}
return params
}

func SplitQuery(path string) (string, string) {
parts := strings.Split(path, "?")
if len(parts) == 1 {
return parts[0], ""
}
return parts[0], parts[1]
}

0 comments on commit 2e76f4d

Please sign in to comment.