a8m / a8m/reflect-examples

Use reflection to dump context

Open Beginner friendly
#6 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
No language data
Stars
568
Forks
73
PR merge metrics
No merged PRs in 30d

Description

Sometimes for local debugging, using [reflection to dump the context](https://stackoverflow.com/a/60278058/2904179) is handy:
```
func printContextInternals(ctx interface{}, inner bool) {
contextValues := reflect.ValueOf(ctx).Elem()
contextKeys := reflect.TypeOf(ctx).Elem()

if !inner {
fmt.Printf("\nFields for %s.%s\n", contextKeys.PkgPath(), contextKeys.Name())
}

if contextKeys.Kind() == reflect.Struct {
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" {
printContextInternals(reflectValue.Interface(), true)
} else {
fmt.Printf("field name: %+v\n", reflectField.Name)
fmt.Printf("value: %+v\n", reflectValue.Interface())
}
}
} else {
fmt.Printf("context is empty (int)\n")
}
}
```

Thanks for putting all your examples in one central place!

Contributor guide

No contributing guide indexed for this repository

Research direction

The issue suggests adding a reflection-based debugging utility for Go contexts. Look at the existing examples in the repository to understand the structure and naming. The function provided can be adapted into a new example file, likely in a directory like 'context' or 'debug'. Ensure the example compiles and runs, demonstrating how to inspect context internals. Check for any existing tests to see how examples are validated.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
75/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.