Adds middleware set userid on context method.

This commit is contained in:
Deepak Mallubhotla 2021-01-25 14:50:54 -06:00
parent 4d093ed99a
commit 93a5e9c1ba
Signed by: deepak
GPG Key ID: 64BF53A3369104E7
2 changed files with 15 additions and 0 deletions

View File

@ -67,6 +67,11 @@ func GetUserID(ctx context.Context) (int, error) {
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.
func GetUsername(ctx context.Context) (string, error) {
username, ok := ctx.Value(usernameCtxKey).(string)

View File

@ -37,3 +37,13 @@ func TestBadContext(t *testing.T) {
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)
}