Skip to content

Instantly share code, notes, and snippets.

@panzhongxian
Created August 6, 2023 11:35
Show Gist options
  • Save panzhongxian/2c8f2e53c5c7aa3fe5f78eabd5651232 to your computer and use it in GitHub Desktop.
Save panzhongxian/2c8f2e53c5c7aa3fe5f78eabd5651232 to your computer and use it in GitHub Desktop.
Dump all key-values in context.
func DumpContextKV(ctx interface{}) map[any]any {
ret := make(map[any]any)
contextKeys := reflect.TypeOf(ctx).Elem()
contextValues := reflect.ValueOf(ctx).Elem()
if contextKeys.Kind() != reflect.Struct {
return ret
}
var key, val any
found := false
for i := 0; i < contextValues.NumField(); i++ {
reflectValue := contextValues.Field(i)
reflectValue = reflect.NewAt(reflectValue.Type(), unsafe.Pointer(reflectValue.UnsafeAddr())).Elem()
reflectField := contextKeys.Field(i)
if reflectField.Name == "Context" {
tmpMap := dumpContextInternals(reflectValue.Interface())
for k, v := range tmpMap {
ret[k] = v
}
} else if reflectField.Name == "cancelCtx" {
tmpMap := dumpContextInternals(reflectValue.FieldByName("Context").Interface())
for k, v := range tmpMap {
ret[k] = v
}
} else if reflectField.Name == "key" {
found = true
key = reflectValue.Interface()
} else if reflectField.Name == "val" {
val = reflectValue.Interface()
}
}
if found {
ret[key] = val
}
return ret
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment