* ok, this is kinda experimental, I don't know how bad of an idea it is .. */
(target string, value string, evt *pipeline.Event)
| 22 | |
| 23 | /* ok, this is kinda experimental, I don't know how bad of an idea it is .. */ |
| 24 | func SetTargetByName(target string, value string, evt *pipeline.Event) bool { |
| 25 | if evt == nil { |
| 26 | return false |
| 27 | } |
| 28 | |
| 29 | // it's a hack, we do it for the user |
| 30 | target = strings.TrimPrefix(target, "evt.") |
| 31 | |
| 32 | log.Debugf("setting target %s to %s", target, value) |
| 33 | |
| 34 | defer func() { |
| 35 | if r := recover(); r != nil { |
| 36 | log.Errorf("Runtime error while trying to set '%s': %+v", target, r) |
| 37 | return |
| 38 | } |
| 39 | }() |
| 40 | |
| 41 | iter := reflect.ValueOf(evt).Elem() |
| 42 | if !iter.IsValid() || iter.IsZero() { |
| 43 | log.Trace("event is nil") |
| 44 | return false |
| 45 | } |
| 46 | |
| 47 | for f := range strings.SplitSeq(target, ".") { |
| 48 | /* |
| 49 | ** According to current Event layout we only have to handle struct and map |
| 50 | */ |
| 51 | switch iter.Kind() { //nolint:exhaustive |
| 52 | case reflect.Map: |
| 53 | tmp := iter.MapIndex(reflect.ValueOf(f)) |
| 54 | // if we're in a map and the field doesn't exist, the user wants to add it :) |
| 55 | if !tmp.IsValid() || tmp.IsZero() { |
| 56 | log.Debugf("map entry is zero in '%s'", target) |
| 57 | } |
| 58 | |
| 59 | iter.SetMapIndex(reflect.ValueOf(f), reflect.ValueOf(value)) |
| 60 | |
| 61 | return true |
| 62 | case reflect.Struct: |
| 63 | tmp := iter.FieldByName(f) |
| 64 | if !tmp.IsValid() { |
| 65 | log.Debugf("'%s' is not a valid target because '%s' is not valid", target, f) |
| 66 | return false |
| 67 | } |
| 68 | |
| 69 | if tmp.Kind() == reflect.Ptr { |
| 70 | tmp = reflect.Indirect(tmp) |
| 71 | } |
| 72 | |
| 73 | iter = tmp |
| 74 | case reflect.Ptr: |
| 75 | tmp := iter.Elem() |
| 76 | iter = reflect.Indirect(tmp.FieldByName(f)) |
| 77 | default: |
| 78 | log.Errorf("unexpected type %s in '%s'", iter.Kind(), target) |
| 79 | return false |
| 80 | } |
| 81 | } |