Created
April 13, 2020 14:31
-
-
Save mannion007/5cbab1ca5d1d755f6ae9d491cf3849de to your computer and use it in GitHub Desktop.
Ninja Level 3 Hands on Exercise #2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
"time" | |
"github.com/mannion007/whatever/session" | |
) | |
func main() { | |
ctx := context.Background() | |
ctx, cancel := context.WithTimeout(ctx, time.Second) | |
defer cancel() | |
ctx = session.WithUserID(ctx, 500) | |
ctx = session.WithUserIP(ctx, "127.0.0.1") | |
fmt.Println(*session.UserIDFrom(ctx)) | |
fmt.Println(*session.UserIPFrom(ctx)) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package session | |
import "context" | |
type userIDKey int | |
type userIPKey int | |
var userID userIDKey = 0 | |
var userIP userIPKey = 1 | |
// WithUserID decorates the supplied context with the supplied User ID | |
func WithUserID(ctx context.Context, id int) context.Context { | |
return context.WithValue(ctx, userID, id) | |
} | |
// WithUserIP decorates the supplied context with the supplied User IP | |
func WithUserIP(ctx context.Context, ip string) context.Context { | |
return context.WithValue(ctx, userIP, ip) | |
} | |
// UserIDFrom extracts the User ID from the supplied context | |
func UserIDFrom(ctx context.Context) *int { | |
value, ok := ctx.Value(userID).(int) | |
if !ok { | |
return nil | |
} | |
return &value | |
} | |
// UserIPFrom extracts the User IP from the supplied context | |
func UserIPFrom(ctx context.Context) *string { | |
value, ok := ctx.Value(userIP).(string) | |
if !ok { | |
return nil | |
} | |
return &value | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment