Skip to content

Instantly share code, notes, and snippets.

@mannion007
Created April 13, 2020 14:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mannion007/5cbab1ca5d1d755f6ae9d491cf3849de to your computer and use it in GitHub Desktop.
Save mannion007/5cbab1ca5d1d755f6ae9d491cf3849de to your computer and use it in GitHub Desktop.
Ninja Level 3 Hands on Exercise #2
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))
}
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