-
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added middleware to set IP address to request context + helpers
- Loading branch information
1 parent
be2ae3d
commit edddaa8
Showing
2 changed files
with
40 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
package clientip | ||
|
||
import "context" | ||
|
||
// contextKey is a type used for keys in the context. | ||
// These keys are used to store and retrieve values from the context. | ||
// The keys are unique and are used to avoid conflicts with other keys. | ||
type contextKey struct{ name string } | ||
|
||
// requestIPKey is the key used to store the client's IP address in the request context. | ||
var requestIPKey = contextKey{"request_ip"} | ||
|
||
// SetIPAddress sets the client's IP address in the request context. | ||
// This IP address can be used in the next handler. | ||
func SetIPAddress(ctx context.Context, ip string) context.Context { | ||
return context.WithValue(ctx, requestIPKey, ip) | ||
} | ||
|
||
// GetIPAddress gets the client's IP address from the request context. | ||
// If the IP address is not found in the context, it returns an empty string. | ||
func GetIPAddress(ctx context.Context) string { | ||
if ip, ok := ctx.Value(requestIPKey).(string); ok { | ||
return ip | ||
} | ||
return "" | ||
} |
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