|
1 | | -# GO dynamic struct |
| 1 | +# Golang dynamic struct |
2 | 2 |
|
3 | | -In progress... |
| 3 | +*Still in progress* |
| 4 | + |
| 5 | +Package dynamic struct provides possibility to dynamically, in runtime, |
| 6 | +extend existing defined structs or to provide completely new struct. |
| 7 | + |
| 8 | +Main features: |
| 9 | +* Building completely new struct in runtime |
| 10 | +* Extending existing struct in runtime |
| 11 | +* Adding new fields into struct |
| 12 | +* Removing existing fields from struct |
| 13 | +* Modifying fields' types and tags |
| 14 | + |
| 15 | +Works out-of-the-box with: |
| 16 | +* https://github.com/go-playground/form |
| 17 | +* https://github.com/go-playground/validator |
| 18 | +* https://github.com/leebenson/conform |
| 19 | +* https://golang.org/pkg/encoding/json/ |
| 20 | + |
| 21 | +Examples: |
| 22 | +```go |
| 23 | +package main |
| 24 | + |
| 25 | +import ( |
| 26 | +"encoding/json" |
| 27 | +"fmt" |
| 28 | +"log" |
| 29 | + |
| 30 | +"github.com/ompluscator/dynamic-struct" |
| 31 | +) |
| 32 | + |
| 33 | +func main() { |
| 34 | +instance := dynamic_struct.NewBuilder(). |
| 35 | +AddField("Integer", 0, `json:"int"`). |
| 36 | +AddField("Text", "", `json:"someText"`). |
| 37 | +AddField("Float", 0.0, `json:"double"`). |
| 38 | +AddField("Boolean", false, ""). |
| 39 | +AddField("Slice", []int{}, ""). |
| 40 | +AddField("Anonymous", "", `json:"-"`). |
| 41 | +Build() |
| 42 | + |
| 43 | +data := []byte(` |
| 44 | +{ |
| 45 | + "int": 123, |
| 46 | + "someText": "example", |
| 47 | + "double": 123.45, |
| 48 | + "Boolean": true, |
| 49 | + "Slice": [1, 2, 3], |
| 50 | + "Anonymous": "avoid to read", |
| 51 | + "NilFloat": 567 |
| 52 | +} |
| 53 | +`) |
| 54 | + |
| 55 | +err := json.Unmarshal(data, &instance) |
| 56 | +if err != nil { |
| 57 | +log.Fatal(err) |
| 58 | +} |
| 59 | + |
| 60 | +data, err = json.Marshal(instance) |
| 61 | +if err != nil { |
| 62 | +log.Fatal(err) |
| 63 | +} |
| 64 | + |
| 65 | +fmt.Println(string(data)) |
| 66 | +// Out: |
| 67 | +// {"int":123,"someText":"example","double":123.45,"Boolean":true,"Slice":[1,2,3]} |
| 68 | +} |
| 69 | +``` |
0 commit comments