options.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package interpol
  2. import "io"
  3. // Options contains all options supported by an Interpolator.
  4. type Options struct {
  5. Template io.Reader
  6. Format Func
  7. Output io.Writer
  8. }
  9. // Option is an option that can be applied to an Interpolator.
  10. type Option func(OptionSetter)
  11. // OptionSetter is an interface that contains the setters for all options
  12. // supported by Interpolator.
  13. type OptionSetter interface {
  14. SetTemplate(template io.Reader)
  15. SetFormat(format Func)
  16. SetOutput(output io.Writer)
  17. }
  18. // WithTemplate assigns Template to Options.
  19. func WithTemplate(template io.Reader) Option {
  20. return func(setter OptionSetter) {
  21. setter.SetTemplate(template)
  22. }
  23. }
  24. // WithFormat assigns Format to Options.
  25. func WithFormat(format Func) Option {
  26. return func(setter OptionSetter) {
  27. setter.SetFormat(format)
  28. }
  29. }
  30. // WithOutput assigns Output to Options.
  31. func WithOutput(output io.Writer) Option {
  32. return func(setter OptionSetter) {
  33. setter.SetOutput(output)
  34. }
  35. }
  36. type optionSetter struct {
  37. opts *Options
  38. }
  39. func newOptionSetter(opts *Options) *optionSetter {
  40. return &optionSetter{opts: opts}
  41. }
  42. func (s *optionSetter) SetTemplate(template io.Reader) {
  43. s.opts.Template = template
  44. }
  45. func (s *optionSetter) SetFormat(format Func) {
  46. s.opts.Format = format
  47. }
  48. func (s *optionSetter) SetOutput(output io.Writer) {
  49. s.opts.Output = output
  50. }
  51. func setOptions(opts []Option, setter OptionSetter) {
  52. for _, opt := range opts {
  53. opt(setter)
  54. }
  55. }