Comments (2)
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.
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)
- Rename example directory to _example
- Add golang 1.16 to Travis CI setting
- Migrate to go-kasumi
- H4K3R HOT 1
- Set up scheduler's logger in favor of robfig/cron improvement
- New HOT 1
- Race condition on live configuration update HOT 1
- Find suitable replacement for forked github.com/robfig/cron. HOT 4
- xmpp adapter HOT 9
- Remove Go 1.6 support
- Mattermost Adapter HOT 4
- Plan v2 release HOT 2
- Exclude Message() method from sarah.Input interface HOT 1
- Rename SentAt() method of sarah.Input to TimeStamp() HOT 1
- sarah.Command also receives sarah.Input to return available help text
- Provide high-level interface to run go-sarah
- Bot supervisor should also receive Bot's noteworthy state in addition to currently handled critical state HOT 1
- Employ xerrors to propagate original error values HOT 1
- Generalize watcher interface
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from go-sarah.