github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/yaml/cusomized.md (about) 1 # customized features 2 3 ## using 4 5 in go.mod as [Using forked package import in Go](https://stackoverflow.com/a/56792766) 6 7 ``` 8 replace github.com/bingoohuang/go-yaml => github.com/bingoohuang/go-yaml v1.8.11-0.20210719040622-7e6a9879a76a 9 ``` 10 11 If you are using go modules. You could use replace directive 12 13 The replace directive allows you to supply another import path that might be another module located in VCS (GitHub or 14 elsewhere), or on your local filesystem with a relative or absolute file path. The new import path from the replace 15 directive is used without needing to update the import paths in the actual source code. 16 17 So you could do below in your go.mod file 18 19 `module github.com/yogeshlonkar/openapi-to-postman` 20 21 go 1.12 22 23 ``` 24 require ( 25 github.com/someone/repo v1.20.0 26 ) 27 28 29 replace github.com/someone/repo => github.com/you/repo v3.2.1 30 ``` 31 32 where v3.2.1 is tag on your repo. Also can be done through CLI 33 34 go mod edit -replace="github.com/someone/repo@v0.0.0=github.com/you/repo@v1.1.1" 35 36 ## decoding by struct field type 37 38 ```go 39 type Duration struct { 40 Dur time.Duration 41 } 42 43 func decodeDuration(node ast.Node, typ reflect.Type) (reflect.Value, error) { 44 if v, ok := node.(*ast.StringNode); ok { 45 d, err := time.ParseDuration(v.Value) 46 return reflect.ValueOf(d), err 47 } 48 return reflect.Value{}, yaml.ErrContinue 49 } 50 51 func TestDecoderDuration(t *testing.T) { 52 c := Duration{} 53 decodeOption := yaml.TypeDecoder(reflect.TypeOf((*time.Duration)(nil)).Elem(), decodeDuration) 54 decoder := yaml.NewDecoder(strings.NewReader(`dur: 10s`), decodeOption) 55 err := decoder.Decode(&c) 56 assert.Nil(t, err) 57 assert.Equal(t, Duration{Dur: 10 * time.Second}, c) 58 59 decoder = yaml.NewDecoder(strings.NewReader(`dur: 111`), decodeOption) 60 err = decoder.Decode(&c) 61 assert.Nil(t, err) 62 assert.Equal(t, Duration{Dur: 111}, c) 63 } 64 ``` 65 66 ## decoding function by label 67 68 ```go 69 type Config struct { 70 Size int64 `yaml:",label=size"` 71 } 72 73 func decodeSize(node ast.Node, typ reflect.Type) (reflect.Value, error) { 74 if s, ok := node.(*ast.StringNode); ok { 75 if v, err := man.ParseBytes(s.Value); err != nil { 76 return reflect.Value{}, err 77 } else { 78 return yaml.CastUint64(v, typ) 79 } 80 } 81 return reflect.Value{}, yaml.ErrContinue 82 } 83 84 func TestDecoderLabel(t *testing.T) { 85 c := Config{} 86 decodeOption := yaml.LabelDecoder("size", decodeSize) 87 decoder := yaml.NewDecoder(strings.NewReader(`size: 10MiB`), decodeOption) 88 err := decoder.Decode(&c) 89 assert.Nil(t, err) 90 assert.Equal(t, Config{Size: 10 * 1024 * 1024}, c) 91 92 decoder = yaml.NewDecoder(strings.NewReader(`size: 1234`), decodeOption) 93 err = decoder.Decode(&c) 94 assert.Nil(t, err) 95 assert.Equal(t, Config{Size: 1234}, c) 96 } 97 ```