Skip to content

Commit e504a05

Browse files
Merge pull request #77 from chriskempf-wf/path_trim
RM-16227 Add path trimming middleware with unit tests
2 parents 9659a8b + dedca68 commit e504a05

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

rest/middleware/path_trim.go

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package middleware
2+
3+
import(
4+
"net/http"
5+
"strings"
6+
7+
"github.com/Workiva/go-rest/rest"
8+
)
9+
10+
// NewPathTrimMiddleware returns a Middleware which inspects request paths
11+
// and removes the content of trimPortion from the prefix. With a path of /foo/bar
12+
// and a trimpPortion of /foo you would be left with a path of /bar.
13+
func NewPathTrimMiddleware(trimPortion string) rest.Middleware {
14+
return func(w http.ResponseWriter, r *http.Request) *rest.MiddlewareError {
15+
r.URL.Path = strings.TrimPrefix(r.URL.Path, trimPortion)
16+
return nil
17+
}
18+
}

rest/middleware/path_trim_test.go

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package middleware
2+
3+
import (
4+
"net/http"
5+
"net/http/httptest"
6+
"testing"
7+
8+
"github.com/stretchr/testify/assert"
9+
)
10+
11+
// Ensure that PathTrimMiddleware is correctly trimming the request path
12+
func TestPathTrimMiddlewareTrimPrefix(t *testing.T) {
13+
assert := assert.New(t)
14+
req, _ := http.NewRequest("GET", "http://example.com/foo/bar", nil)
15+
w := httptest.NewRecorder()
16+
17+
assert.Nil(NewPathTrimMiddleware("/foo")(w, req))
18+
assert.Equal(req.URL.Path, "/bar")
19+
}
20+
21+
// Ensure that PathTrimMiddleware correclty passes a path that doesn't need
22+
// to be trimmed
23+
func TestPathTrimMiddlewareNoTrimPrefix(t *testing.T) {
24+
assert := assert.New(t)
25+
req, _ := http.NewRequest("GET", "http://example.com/foo/bar", nil)
26+
w := httptest.NewRecorder()
27+
28+
assert.Nil(NewPathTrimMiddleware("/baz")(w, req))
29+
assert.Equal(req.URL.Path, "/foo/bar")
30+
}

0 commit comments

Comments
 (0)