Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/xsleonard/gopts
Self-referential struct configuration
https://github.com/xsleonard/gopts
Last synced: 1 day ago
JSON representation
Self-referential struct configuration
- Host: GitHub
- URL: https://github.com/xsleonard/gopts
- Owner: xsleonard
- License: mit
- Created: 2014-01-28T18:09:57.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2014-01-28T23:31:47.000Z (over 10 years ago)
- Last Synced: 2024-06-21T03:18:51.844Z (3 months ago)
- Language: Go
- Homepage:
- Size: 160 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
gopts
=====[![Build Status](https://drone.io/github.com/xsleonard/gopts/status.png)](https://drone.io/github.com/xsleonard/gopts/latest)
Self-referential struct configuration.
This package was inspired by http://commandcenter.blogspot.com/2014/01/self-referential-functions-and-design.html
Documentation: [![GoDoc](https://godoc.org/github.com/xsleonard/gopts?status.png)](http://godoc.org/github.com/xsleonard/gopts)
## Example
```go
import "gopts"var (
Port = gopts.Option("Config.Port", uint16(7777))
Network = gopts.Option("Network", "tcp")
)type ServerConfig struct {
Port uint16
}type Server struct {
Network string
Config ServerConfig
}func NewServer(opts ...gopts.OptSetter) *Server {
s := &Server{}
// set defaults
gopts.Set(s, Port(), Network())
// override defaults with user's values
gopts.Set(s, opts...)
return s
}func updateServer() {
s := NewServer(Network("udp"))
// s.Config.Port == 7777
// s.Network == "udp"// Set multiple options
prevOpts := gopts.Set(s, Port(uint16(6666)), Network("tcp"))
// s.Config.Port == 6666
// s.Network == "tcp"// Reset to the previous values. These two statements are equivalent.
prevOpts = gopts.Set(s, prevOpts...)
// s.Config.Port == 7777
// s.Config.Network == "udp"// Shorthand for setting a single option:
prevOpts[0](s)
// s.Config.Port == 6666
}
```