Skip to content

Commit f45124c

Browse files
committed
Create module to parse path and extract id value
1 parent 0cd43dd commit f45124c

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

api/path.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package main
2+
3+
import "strings"
4+
5+
const PathSeparator = "/"
6+
7+
type Path struct {
8+
Path string
9+
ID string
10+
}
11+
12+
func NewPath(p string) *Path {
13+
var id string
14+
p = strings.Trim(p, PathSeparator)
15+
s := strings.Split(p, PathSeparator)
16+
if len(s) > 1 {
17+
lastIndex := len(s) - 1
18+
id = s[lastIndex]
19+
p = strings.Join(s[:lastIndex], PathSeparator)
20+
}
21+
return &Path{Path: p, ID: id}
22+
}
23+
24+
func (p *Path) HasID() bool {
25+
return len(p.ID) > 0
26+
}

api/path_test.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package main
2+
3+
import "testing"
4+
5+
func TestNewPath(t *testing.T) {
6+
for _, testCase := range getTestCases() {
7+
newPath := NewPath(testCase.OriginalPath)
8+
if testCase.Path != newPath.Path {
9+
t.Errorf("Error parsing the path, we expected %s, got %s", testCase.Path, newPath.Path)
10+
}
11+
12+
if testCase.HasId != newPath.HasID() {
13+
t.Errorf("Error checking the has id, we expected %v, got %v", testCase.HasId, newPath.HasID())
14+
}
15+
16+
if testCase.ID != newPath.ID {
17+
t.Errorf("Error getting the identifier, we expected %s, got %s", testCase.ID, newPath.ID)
18+
}
19+
}
20+
}
21+
22+
type newPathTestCase struct {
23+
OriginalPath string
24+
Path string
25+
ID string
26+
HasId bool
27+
}
28+
29+
func getTestCases() []newPathTestCase {
30+
return []newPathTestCase{
31+
{OriginalPath: "/", Path: "", ID: "", HasId: false},
32+
{OriginalPath: "/people/", Path: "people", ID: "", HasId: false},
33+
{OriginalPath: "/people/1", Path: "people", ID: "1", HasId: true},
34+
}
35+
}

0 commit comments

Comments
 (0)