Skip to content

Instantly share code, notes, and snippets.

@munir131
Created August 4, 2020 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save munir131/e01c94e144ff3d9283164a5aad6c4881 to your computer and use it in GitHub Desktop.
Save munir131/e01c94e144ff3d9283164a5aad6c4881 to your computer and use it in GitHub Desktop.
This function will help to print context in Golang. Credit: https://stackoverflow.com/users/959140/robin-andersson
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")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment