Skip to content

Instantly share code, notes, and snippets.

@Petelin
Created July 16, 2020 09:16
Show Gist options
  • Save Petelin/09136cf7dbe6e4a2ba58296027c45d02 to your computer and use it in GitHub Desktop.
Save Petelin/09136cf7dbe6e4a2ba58296027c45d02 to your computer and use it in GitHub Desktop.
rpc 中间打印
func fieldSet(fields ...string) map[string]bool {
set := make(map[string]bool, len(fields))
for _, s := range fields {
set[s] = true
}
return set
}
func IgnoreFields(v interface{}, fields ...string) map[string]interface{} {
ignoreMap := fieldSet(fields...)
rv := reflect.Indirect(reflect.ValueOf(v))
rt := rv.Type()
out := make(map[string]interface{}, rt.NumField())
for i := 0; i < rt.NumField(); i++ {
field := rt.Field(i)
jsonKey := field.Tag.Get("json")
if (jsonKey != "" && ignoreMap[jsonKey]) || ignoreMap[field.Name] {
continue
}
out[field.Name] = rv.Field(i).Interface()
}
return out
}
func DebugMiddleware(next endpoint.EndPoint) endpoint.EndPoint {
return func(ctx context.Context, request interface{}) (response interface{}, err error) {
response, err = next(ctx, request)
if env.IsStaging() && !common.IsTCE() {
reqStr := marshalWithIgnoreKey(request, "Base")
respStr := marshalWithIgnoreKey(response, "BaseResp", "Base")
method, _ := kitutil.GetCtxMethod(ctx)
log.Logger(ctx).Debugf("[KiteHandler] %s request:%v =========== resp=%v", method, reqStr, respStr)
}
return
}
}
func marshalWithIgnoreKey(v interface{}, keys ...string) string {
rv := reflect.Indirect(reflect.ValueOf(v))
if rv.NumField() > 0 {
v = rv.Field(0).Interface()
}
return fmt.Sprintf("%v", IgnoreFields(v, keys...))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment