From cb9c80758ce4ef49c450ec2e289d200422c30018 Mon Sep 17 00:00:00 2001 From: Sameer Ajmani Date: Mon, 28 Jul 2014 21:01:30 -0400 Subject: go.blog/context: an article about go.net/context.Context. Blog demo (internal): http://olivia.nyc.corp.google.com:8081/context Server demo (internal): http://olivia.nyc.corp.google.com:8080/search?q=golang&timeout=1s LGTM=bcmills, adg, r R=r, rsc, adg, bcmills, ken, adonovan, dsymonds, crawshaw, campoy, hakim, dneil https://golang.org/cl/116820044 --- content/context/userip/userip.go | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 content/context/userip/userip.go (limited to 'content/context/userip') diff --git a/content/context/userip/userip.go b/content/context/userip/userip.go new file mode 100644 index 0000000..3001ade --- /dev/null +++ b/content/context/userip/userip.go @@ -0,0 +1,38 @@ +// Package userip provides functions for extracting a user IP address from a +// request and associating it with a Context. +package userip + +import ( + "fmt" + "net" + "net/http" + "strings" + + "code.google.com/p/go.net/context" +) + +// FromRequest extracts the user IP address from req, if present. +func FromRequest(req *http.Request) (net.IP, error) { + s := strings.SplitN(req.RemoteAddr, ":", 2) + userIP := net.ParseIP(s[0]) + if userIP == nil { + return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr) + } + return userIP, nil +} + +// The address &key is the context key. +var key struct{} + +// NewContext returns a new Context carrying userIP. +func NewContext(ctx context.Context, userIP net.IP) context.Context { + return context.WithValue(ctx, &key, userIP) +} + +// FromContext extracts the user IP address from ctx, if present. +func FromContext(ctx context.Context) (net.IP, bool) { + // ctx.Value returns nil if ctx has no value for the key; + // the net.IP type assertion returns ok=false for nil. + userIP, ok := ctx.Value(&key).(net.IP) + return userIP, ok +} -- cgit v1.2.3