Created
August 4, 2020 05:58
-
-
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
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
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