Skip to content

Commit

Permalink
Helper functions to read path elements.
Browse files Browse the repository at this point in the history
  • Loading branch information
joliver committed Jun 5, 2021
1 parent dfa68a3 commit e22bc75
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
35 changes: 35 additions & 0 deletions functions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package shuttle

import (
"strconv"
"strings"
)

func ReadPathElement(rawPath, upstreamElement string) string {
var nextDocument bool
var document string
for len(rawPath) > 0 {
slashIndex := strings.Index(rawPath, "/")
if slashIndex >= 0 {
document, rawPath = rawPath[:slashIndex], rawPath[slashIndex+1:]
} else {
document = rawPath
rawPath = ""
}

if nextDocument {
return document
}

if document == upstreamElement {
nextDocument = true
}
}

return ""
}
func ReadNumericPathElement(rawPath, upstreamElement string) uint64 {
raw := ReadPathElement(rawPath, upstreamElement)
value, _ := strconv.ParseUint(raw, 10, 64)
return value
}
25 changes: 25 additions & 0 deletions functions_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package shuttle

import "testing"

func TestReadPathElement(t *testing.T) {
assertPathElement(t, "/path/users/value", "users", "value")
assertPathElement(t, "/path/users/value/", "users", "value")
assertPathElement(t, "/path/users/value/other/stuff", "users", "value")
}
func assertPathElement(t *testing.T, raw, element, expected string) {
Assert(t).That(ReadPathElement(raw, element)).Equals(expected)
}

func TestReadNumericPathElement(t *testing.T) {
assertNumericPathElement(t, "/path/users/123", "users", 123)
assertNumericPathElement(t, "/path/users/123/", "users", 123)
assertNumericPathElement(t, "/path/users/123/other/stuff", "users", 123)
assertNumericPathElement(t, "/path/users/-123/other/stuff", "users", 0)
assertNumericPathElement(t, "/path/users/abc/other/stuff", "users", 0)
assertNumericPathElement(t, "/path/users/abc123/other/stuff", "users", 0)
assertNumericPathElement(t, "/path/users/_123/other/stuff", "users", 0)
}
func assertNumericPathElement(t *testing.T, raw, element string, expected uint64) {
Assert(t).That(ReadNumericPathElement(raw, element)).Equals(expected)
}

0 comments on commit e22bc75

Please sign in to comment.