Coder Social home page Coder Social logo

Comments (2)

oklahomer avatar oklahomer commented on May 18, 2024

The previous code does not consider saving pre-set values. When default field value is set before unmarshal and the input JSON structure does not contain the field, the pre-set default value should stay as-is. This is vital with this project's usage of constructor method as below:

// NewConfig returns Config instance with default configuration values.
// To override with desired value, pass the returned instance to json.Unmarshal or yaml.Unmarshal.
func NewConfig() *Config {
	return &Config{
		WorkerNum:         100,
		QueueSize:         10,
		SuperviseInterval: 60 * time.Second,
	}
}

To let default value stay as-is, implementation should be somewhat like below:

// duration is an alias type that can be widely used in this project's JSON deserialization.
// Could be capitalized when sub-packages also require the same mechanism.
type duration time.Duration

// UnmarshalJSON receives both time.ParseDuration-friendly string and simple int.
func (d *duration) UnmarshalJSON(b []byte) error {
	s := string(b)

	// First, see if given value is int
	i, err := strconv.Atoi(s)
	if err == nil {
		*d = duration(i)
		return nil
	}

	// Consider given value is a quoted string such as "1.5h" and "2h45m"
	s, err = strconv.Unquote(s)
	v, err := time.ParseDuration(s)
	if err != nil {
		return err
	}

	*d = duration(v)
	return nil
}

type Config struct {
	Token          string        `json:"token" yaml:"token"`
	RequestTimeout time.Duration `json:"timeout" yaml:"timeout"` // Let the field definition stay as-is to avoid external code change.
}

// UnmarshalJSON uses temporary struct to map received JSON structure.
func (config *Config) UnmarshalJSON(raw []byte) error {
	// Embedding the original struct ends up with calling Config.UnmarshalJSON infinitely.
	// Just create an alias to Config and embed this, instead.
	type C Config
	tmp := &struct {
		C
		RequestTimeout *duration `json:"timeout"` // Add extra field that points to the same JSON field
	}{
		// Inherit pre-set field values. Will be overridden if new value exists in JSON structure.
		C: C(*config),
	}

	err := json.Unmarshal(raw, tmp)
	if err != nil {
		return err
	}

	// Automatically copy all marshaled values from temporary struct to original.
	// Since pre-set value is set to temporary struct before deserialization,
	// both pre-set value and overridden values are copied properly.
	rv := reflect.ValueOf(config)
	tmpV := reflect.ValueOf(tmp.C)
	tmpT := reflect.TypeOf(tmp.C)
	for i := 0; i < tmpT.NumField(); i++ {
		rv.Elem().FieldByName(tmpT.Field(i).Name).Set(tmpV.Field(i))
	}

	// If time.Duration is set, override.
	if tmp.RequestTimeout != nil {
		config.RequestTimeout = time.Duration(*tmp.RequestTimeout)
	}

	return nil
}

And yaml handling is no longer necessary because yaml.v2 already handles time.Duration field with time.ParseDuration. It is questionable that if time.ParseDuration support is required for JSON, too. The above example became a bit tricky to do below:

  • Automatically cover all fields of original struct
  • Apply all updated values to original struct
  • When one or more fields are added to original struct, the temporary struct follows the same without any code change
    Take some time before applying this change to this project.

from go-sarah.

oklahomer avatar oklahomer commented on May 18, 2024

Not implementing this for now. Already found out yaml.v2 properly handles time.Duration serialization, and that should be enough to parse configuration files since YAML format seems to be more popular as configuration file structure.

from go-sarah.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.