Advertisement
Guest User

Untitled

a guest
May 12th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. package config
  2.  
  3. import (
  4. "fmt"
  5. "gopkg.in/yaml.v2"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. )
  10.  
  11. type Config struct {
  12. Server ServerConfig `yaml:"server"`
  13. Steam SteamConfig `yaml:"steam"`
  14. Telegram TelegramConfig `yaml:"telegram"`
  15. Postgres PostgresConfig `yaml:"postgres"`
  16. Watcher WatcherConfig `yaml:"watcher"`
  17. }
  18.  
  19. type WatcherConfig struct {
  20. Tick int `yaml:"tick"`
  21. }
  22.  
  23. type ServerConfig struct {
  24. Host string `yaml:"host"`
  25. Port int `yaml:"port"`
  26. Protocol string `yaml:"protocol"`
  27. Timeout int `yaml:"timeout"`
  28. }
  29.  
  30. type SteamConfig struct {
  31. Key string `yaml:"key"`
  32. Host string `yaml:"host"`
  33. }
  34.  
  35. type TelegramConfig struct {
  36. Key string `yaml:"key"`
  37. }
  38.  
  39. type PostgresConfig struct {
  40. DBname string `yaml:"dbname"`
  41. Host string `yaml:"host"`
  42. Port int `yaml:"port"`
  43. User string `yaml:"user"`
  44. Password string `yaml:"password"`
  45. SSLMode string `yaml:"sslmode"`
  46. }
  47.  
  48. func (pg *PostgresConfig) DSN() string {
  49. sslmode := "disable"
  50. if pg.SSLMode != "" {
  51. sslmode = pg.SSLMode
  52. }
  53.  
  54. return fmt.Sprintf(
  55. "user=%s password=%s port=%d host=%s dbname=%s sslmode=%s",
  56. pg.User,
  57. pg.Password,
  58. pg.Port,
  59. pg.Host,
  60. pg.DBname,
  61. sslmode,
  62. )
  63. }
  64.  
  65. func LoadConfig(filepath string) *Config {
  66. config := &Config{
  67. Server: ServerConfig{
  68. Host: "localhost",
  69. Port: 8080,
  70. Protocol: "http",
  71. Timeout: 30,
  72. },
  73. }
  74. if _, err := os.Stat(filepath); os.IsNotExist(err) {
  75. log.Fatalf("Config file not found! %v", err)
  76. }
  77.  
  78. data, err := ioutil.ReadFile(filepath)
  79. if err != nil {
  80. log.Fatalf("Can't read config file %v", err)
  81. }
  82.  
  83. err = yaml.Unmarshal(data, config)
  84. if err != nil {
  85. log.Fatalf("YAML parse error: %v", err)
  86. }
  87.  
  88. return config
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement