You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1020 B

  1. package config
  2. import (
  3. "go-dht/kademlia"
  4. "github.com/spf13/viper"
  5. "github.com/urfave/cli"
  6. )
  7. type Config struct {
  8. ID string
  9. Addr string
  10. Port string
  11. KnownNodesStr []KnownNodeStr `mapstructure:"knownnodes"`
  12. KnownNodes []kademlia.ListedNode `mapstructure:"-"`
  13. }
  14. type KnownNodeStr struct {
  15. ID string
  16. Addr string
  17. Port string
  18. }
  19. var C Config
  20. func MustRead(c *cli.Context) error {
  21. viper.SetConfigType("yaml")
  22. viper.SetConfigName("config")
  23. viper.AddConfigPath(".")
  24. if c.GlobalString("config") != "" {
  25. viper.SetConfigFile(c.GlobalString("config"))
  26. }
  27. if err := viper.ReadInConfig(); err != nil {
  28. return err
  29. }
  30. if err := viper.Unmarshal(&C); err != nil {
  31. return err
  32. }
  33. for _, v := range C.KnownNodesStr {
  34. id, err := kademlia.IDFromString(v.ID)
  35. if err != nil {
  36. return err
  37. }
  38. kn := kademlia.ListedNode{
  39. ID: id,
  40. Addr: v.Addr,
  41. Port: v.Port,
  42. }
  43. C.KnownNodes = append(C.KnownNodes, kn)
  44. }
  45. C.KnownNodesStr = []KnownNodeStr{}
  46. return nil
  47. }