-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstruct.go
More file actions
56 lines (49 loc) · 1.4 KB
/
struct.go
File metadata and controls
56 lines (49 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package check
import (
"encoding/json"
"fmt"
"reflect"
)
// ParseStruct validates data against a schema, then maps the validated result
// into a Go struct. The target must be a pointer to a struct.
//
// Field mapping uses the "json" struct tag (or lowercase field name if no tag).
//
// Usage:
//
// type User struct {
// Name string `json:"name"`
// Email string `json:"email"`
// Age int `json:"age"`
// Tags []string `json:"tags"`
// }
//
// var user User
// err := check.ParseStruct(schema, data, &user)
func ParseStruct(schema Schema, data any, target any) error {
// Validate first
result, err := schema.Parse(data)
if err != nil {
return err
}
if result == nil {
return nil
}
// Marshal the validated result to JSON, then unmarshal into the struct.
// This leverages Go's built-in JSON struct mapping (json tags, type coercion).
rv := reflect.ValueOf(target)
if rv.Kind() != reflect.Ptr || rv.IsNil() {
return fmt.Errorf("target must be a non-nil pointer to a struct")
}
if rv.Elem().Kind() != reflect.Struct {
return fmt.Errorf("target must be a pointer to a struct, got pointer to %s", rv.Elem().Kind())
}
b, err := json.Marshal(result)
if err != nil {
return fmt.Errorf("internal: failed to marshal validated result: %w", err)
}
if err := json.Unmarshal(b, target); err != nil {
return fmt.Errorf("failed to map result to struct: %w", err)
}
return nil
}