feat service: introduce labels for logs/recorder (#104)
This commit is contained in:
@@ -100,3 +100,17 @@ func ClientIDFromContext(ctx context.Context) ClientID {
|
||||
v, _ := ctx.Value(clientIDKey{}).(ClientID)
|
||||
return v
|
||||
}
|
||||
|
||||
// labelsKey saves the static service labels.
|
||||
type labelsKey struct{}
|
||||
|
||||
// ContextWithLabels returns a new context carrying the given service labels.
|
||||
func ContextWithLabels(ctx context.Context, labels map[string]string) context.Context {
|
||||
return context.WithValue(ctx, labelsKey{}, labels)
|
||||
}
|
||||
|
||||
// LabelsFromContext returns the service labels stored in the context, or nil.
|
||||
func LabelsFromContext(ctx context.Context) map[string]string {
|
||||
v, _ := ctx.Value(labelsKey{}).(map[string]string)
|
||||
return v
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ package ctx
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -149,6 +150,29 @@ func TestClientIDFromContext_WrongType(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestContextWithLabels(t *testing.T) {
|
||||
labels := map[string]string{"tenant": "acme", "region": "eu"}
|
||||
ctx := ContextWithLabels(context.Background(), labels)
|
||||
|
||||
got := LabelsFromContext(ctx)
|
||||
if !reflect.DeepEqual(got, labels) {
|
||||
t.Errorf("LabelsFromContext() = %v, want %v", got, labels)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelsFromContext_Empty(t *testing.T) {
|
||||
if got := LabelsFromContext(context.Background()); got != nil {
|
||||
t.Errorf("LabelsFromContext(empty) = %v, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelsFromContext_WrongType(t *testing.T) {
|
||||
ctx := context.WithValue(context.Background(), labelsKey{}, "not-a-map")
|
||||
if got := LabelsFromContext(ctx); got != nil {
|
||||
t.Errorf("LabelsFromContext(wrong type) = %v, want nil", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultipleValuesInContext(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
ctx = ContextWithSrcAddr(ctx, &net.TCPAddr{IP: net.ParseIP("10.0.0.1"), Port: 8080})
|
||||
|
||||
Reference in New Issue
Block a user