export pathvar for user-defined routers (#911)
* refactor * export pathvar for user-defined routers
This commit is contained in:
29
rest/pathvar/params.go
Normal file
29
rest/pathvar/params.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package pathvar
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var pathVars = contextKey("pathVars")
|
||||
|
||||
// Vars parses path variables and returns a map.
|
||||
func Vars(r *http.Request) map[string]string {
|
||||
vars, ok := r.Context().Value(pathVars).(map[string]string)
|
||||
if ok {
|
||||
return vars
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithVars writes params into given r and returns a new http.Request.
|
||||
func WithVars(r *http.Request, params map[string]string) *http.Request {
|
||||
return r.WithContext(context.WithValue(r.Context(), pathVars, params))
|
||||
}
|
||||
|
||||
type contextKey string
|
||||
|
||||
func (c contextKey) String() string {
|
||||
return "rest/pathvar/context key: " + string(c)
|
||||
}
|
||||
32
rest/pathvar/params_test.go
Normal file
32
rest/pathvar/params_test.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package pathvar
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestVars(t *testing.T) {
|
||||
expect := map[string]string{
|
||||
"a": "1",
|
||||
"b": "2",
|
||||
}
|
||||
r, err := http.NewRequest(http.MethodGet, "/", nil)
|
||||
assert.Nil(t, err)
|
||||
r = r.WithContext(context.WithValue(context.Background(), pathVars, expect))
|
||||
assert.EqualValues(t, expect, Vars(r))
|
||||
}
|
||||
|
||||
func TestVarsNil(t *testing.T) {
|
||||
r, err := http.NewRequest(http.MethodGet, "/", nil)
|
||||
assert.Nil(t, err)
|
||||
assert.Nil(t, Vars(r))
|
||||
}
|
||||
|
||||
func TestContextKey(t *testing.T) {
|
||||
ck := contextKey("hello")
|
||||
assert.True(t, strings.Contains(ck.String(), "hello"))
|
||||
}
|
||||
Reference in New Issue
Block a user