| 29 | } |
| 30 | |
| 31 | func setCallback(value reflect.Value, path Path, cb functionReceived) error { |
| 32 | i := 0 |
| 33 | for { |
| 34 | switch value.Kind() { |
| 35 | case reflect.Slice: |
| 36 | if i == len(path) { |
| 37 | return fmt.Errorf("callback path too short: %v", path) |
| 38 | } |
| 39 | |
| 40 | // Path component may be a string or an integer. |
| 41 | var index int |
| 42 | var err error |
| 43 | switch v := path[i].(type) { |
| 44 | case string: |
| 45 | index, err = strconv.Atoi(v) |
| 46 | if err != nil { |
| 47 | return fmt.Errorf("integer expected in callback path, got '%v'.", path[i]) |
| 48 | } |
| 49 | case float64: |
| 50 | index = int(v) |
| 51 | default: |
| 52 | panic(fmt.Errorf("unknown type: %#v", path[i])) |
| 53 | } |
| 54 | |
| 55 | value = value.Index(index) |
| 56 | i++ |
| 57 | case reflect.Map: |
| 58 | if i == len(path) { |
| 59 | return fmt.Errorf("callback path too short: %v", path) |
| 60 | } |
| 61 | if i == len(path)-1 && value.Type().Elem().Kind() == reflect.Interface { |
| 62 | value.SetMapIndex(reflect.ValueOf(path[i]), reflect.ValueOf(cb)) |
| 63 | return nil |
| 64 | } |
| 65 | value = value.MapIndex(reflect.ValueOf(path[i])) |
| 66 | i++ |
| 67 | case reflect.Ptr: |
| 68 | value = value.Elem() |
| 69 | case reflect.Interface: |
| 70 | if i == len(path) { |
| 71 | value.Set(reflect.ValueOf(cb)) |
| 72 | return nil |
| 73 | } |
| 74 | value = value.Elem() |
| 75 | case reflect.Struct: |
| 76 | if value.Type() == reflect.TypeOf(Function{}) { |
| 77 | caller := value.FieldByName("Caller") |
| 78 | caller.Set(reflect.ValueOf(cb)) |
| 79 | return nil |
| 80 | } |
| 81 | |
| 82 | if innerPartial, ok := value.Addr().Interface().(*Partial); ok { |
| 83 | spec := CallbackSpec{path[i:], Function{cb}} |
| 84 | innerPartial.CallbackSpecs = append(innerPartial.CallbackSpecs, spec) |
| 85 | return nil |
| 86 | } |
| 87 | |
| 88 | // Path component may be a string or an integer. |