cleanenv icon indicating copy to clipboard operation
cleanenv copied to clipboard

Custom Decoder would be nice!!

Open paracha3 opened this issue 5 years ago • 5 comments

paracha3 avatar Feb 25 '20 23:02 paracha3

Hi @paracha3. Could you please give more context about how you want to use such a feature?

ilyakaznacheev avatar Mar 30 '20 21:03 ilyakaznacheev

type Config struct {
    Status enum.Status `yaml:"status" decoder:"Dec"`
}

func(*Config) Dec() {}

🤔

vlaabra avatar May 11 '20 20:05 vlaabra

@vlaabra I need to think about it. Probably some decoder like json.Unmarshaler would be the better approach, but I still don't know about the usage.

Are there any examples of popular decoders, which could be used like this?

ilyakaznacheev avatar May 11 '20 21:05 ilyakaznacheev

import "encoding/hex"
import "go.mongodb.org/mongo-driver/bson/primitive"

type Config struct {
    Decimal primitive.Decimal128 `yaml:"decimal" decoder:"StringToDecimal"` // 12345
    Hex     []byte               `yaml:"hex" decoder:"StringToHex"`         // 1234FF
}

func (c *Config) StringToDecimal(s interface{}) (err error) {
	c.Decimal, err = primitive.ParseDecimal128(fmt.Sprint(s))
	return
}

func (c *Config) StringToHex(s interface{}) (err error) {
	c.Hex, err = hex.DecodeString(fmt.Sprint(s))
	return
}

i need`t, just suggestion

unlike yaml, json calls UnmarshalText and UnmarshalJSON methods if they implementing its interface

vlaabra avatar May 12 '20 00:05 vlaabra

Okay, looks good, we'll add this

ilyakaznacheev avatar May 19 '20 08:05 ilyakaznacheev