ParseInto 解析并绑定到目标 struct
(ctx context.Context, text string, target any)
| 29 | |
| 30 | // ParseInto 解析并绑定到目标 struct |
| 31 | func (tp *TypedParser) ParseInto(ctx context.Context, text string, target any) error { |
| 32 | if target == nil { |
| 33 | return errors.New("target cannot be nil") |
| 34 | } |
| 35 | |
| 36 | // 检查 target 是否为指针 |
| 37 | rv := reflect.ValueOf(target) |
| 38 | if rv.Kind() != reflect.Ptr { |
| 39 | return errors.New("target must be a pointer") |
| 40 | } |
| 41 | |
| 42 | // 提取 JSON |
| 43 | rawJSON, err := extractJSONSegment(text) |
| 44 | if err != nil { |
| 45 | return fmt.Errorf("extract json: %w", err) |
| 46 | } |
| 47 | |
| 48 | // Schema 验证(如果配置) |
| 49 | if tp.validator != nil { |
| 50 | if err := tp.validator.Validate(rawJSON); err != nil { |
| 51 | return fmt.Errorf("schema validation failed: %w", err) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | // 绑定到 struct |
| 56 | if err := json.Unmarshal([]byte(rawJSON), target); err != nil { |
| 57 | return fmt.Errorf("unmarshal to struct: %w", err) |
| 58 | } |
| 59 | |
| 60 | return nil |
| 61 | } |
| 62 | |
| 63 | // ParseIntoWithValidation 解析并进行自定义验证 |
| 64 | func (tp *TypedParser) ParseIntoWithValidation(ctx context.Context, text string, target any, validator func(any) error) error { |