Adds middleware set userid on context method.
This commit is contained in:
parent
4d093ed99a
commit
93a5e9c1ba
@ -67,6 +67,11 @@ func GetUserID(ctx context.Context) (int, error) {
|
|||||||
return int(userID), nil
|
return int(userID), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// SetUserID sets the username field on a context, necessary because the key is an unexported custom type.
|
||||||
|
func SetUserID(ctx context.Context, id int) context.Context {
|
||||||
|
return context.WithValue(ctx, userIDCtxKey, int64(id))
|
||||||
|
}
|
||||||
|
|
||||||
// GetUsername does something similar to GetUserID.
|
// GetUsername does something similar to GetUserID.
|
||||||
func GetUsername(ctx context.Context) (string, error) {
|
func GetUsername(ctx context.Context) (string, error) {
|
||||||
username, ok := ctx.Value(usernameCtxKey).(string)
|
username, ok := ctx.Value(usernameCtxKey).(string)
|
||||||
|
@ -37,3 +37,13 @@ func TestBadContext(t *testing.T) {
|
|||||||
assert.NotNil(err)
|
assert.NotNil(err)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestSetContext(t *testing.T) {
|
||||||
|
assert := assert.New(t)
|
||||||
|
|
||||||
|
idToUse := 3
|
||||||
|
ctx := tokens.SetUserID(context.Background(), 3)
|
||||||
|
receivedID, err := tokens.GetUserID(ctx)
|
||||||
|
assert.Nil(err)
|
||||||
|
assert.EqualValues(idToUse, receivedID)
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user