parser.go 743 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package config
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. )
  7. type ParseMethod func(r io.Reader) (Config, error)
  8. var (
  9. methods = make(map[string]ParseMethod)
  10. )
  11. func RegisterParseMethod(name string, method ParseMethod) {
  12. methods[name] = method
  13. }
  14. func FromReader(methodName string, r io.Reader) (res Config, err error) {
  15. method, check := methods[methodName]
  16. if !check {
  17. return nil, fmt.Errorf("UNEXPECTED METHOD [%v]", methodName)
  18. }
  19. return method(r)
  20. }
  21. func FromFile(methodName, filePath string) (res Config, err error) {
  22. method, check := methods[methodName]
  23. if !check {
  24. return nil, fmt.Errorf("UNEXPECTED METHOD [%v]", methodName)
  25. }
  26. var f *os.File
  27. if f, err = os.Open(filePath); err != nil {
  28. return
  29. }
  30. defer f.Close()
  31. return method(f)
  32. }