Skip to content

Commit

Permalink
last
Browse files Browse the repository at this point in the history
  • Loading branch information
poteto0 committed Oct 19, 2024
1 parent 69531c7 commit c373ab1
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
1 change: 1 addition & 0 deletions constant/constant.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ const (
HEADER_ORIGIN string = "Origin"
HEADER_VARY string = "vary"
MAX_DOMAIN_LENGTH int = 255
PARAM_PREFIX string = ":"
)
41 changes: 31 additions & 10 deletions route.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package poteto

import (
"strings"

"github.com/poteto0/poteto/constant"
)

type Route interface {
Expand All @@ -12,33 +14,42 @@ type Route interface {
}

type route struct {
key string
method string
children map[string]Route
handler HandlerFunc
key string
method string
children map[string]Route
childParamKey string
handler HandlerFunc
}

func NewRoute() Route {
return &route{
key: "",
method: "",
children: make(map[string]Route),
key: "",
method: "",
children: make(map[string]Route),
childParamKey: "",
}
}

func (r *route) Search(path string) *route {
currentRoute := r
params := strings.Split(path, "/")

for _, param := range params {
for i, param := range params {
if param == "" {
continue
}

if nextRoute, ok := currentRoute.children[param]; ok {
currentRoute = nextRoute.(*route)
} else {
return nil
// last path includes url param ex: /users/:id
if i == len(params)-1 && currentRoute.childParamKey != "" {
if nextRoute, ok = currentRoute.children[param]; ok {
currentRoute = nextRoute.(*route)
}
} else {
return nil
}
}
}
return currentRoute
Expand All @@ -48,12 +59,18 @@ func (r *route) Insert(method, path string, handler HandlerFunc) {
currentRoute := r
params := strings.Split(path, "/")

for _, param := range params {
for i, param := range params {
if param == "" {
continue
}

if nextRoute := currentRoute.children[param]; nextRoute == nil {

// last path includes url param ex: /users/:id
if i == len(params)-1 && hasParamPrefix(param) {
currentRoute.childParamKey = param
}

currentRoute.children[param] = &route{
key: param,
method: method,
Expand All @@ -65,6 +82,10 @@ func (r *route) Insert(method, path string, handler HandlerFunc) {
currentRoute.handler = handler
}

func hasParamPrefix(param string) bool {
return strings.HasPrefix(param, constant.PARAM_PREFIX)
}

func (r *route) GetHandler() HandlerFunc {
return r.handler
}

0 comments on commit c373ab1

Please sign in to comment.