conf.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package conf
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "runtime"
  8. "github.com/BurntSushi/toml"
  9. )
  10. type sequenceDB struct {
  11. DSN string `toml:"dsn"`
  12. MaxIdleConns int `toml:"max_idle_conns"`
  13. MaxOpenConns int `toml:"max_open_conns"`
  14. }
  15. type http struct {
  16. Port string `toml:"port"`
  17. }
  18. type shortDB struct {
  19. ReadDSN string `toml:"read_dsn"`
  20. WriteDSN string `toml:"write_dsn"`
  21. MaxIdleConns int `toml:"max_idle_conns"`
  22. MaxOpenConns int `toml:"max_open_conns"`
  23. }
  24. type common struct {
  25. BlackShortURLs []string `toml:"black_short_urls"`
  26. BlackShortURLsMap map[string]bool
  27. BaseString string `toml:"base_string"`
  28. BaseStringLength uint64
  29. DomainName string `toml:"domain_name"`
  30. Schema string `toml:"schema"`
  31. }
  32. type config struct {
  33. Http http `toml:"http"`
  34. SequenceDB sequenceDB `toml:"sequence_db"`
  35. ShortDB shortDB `toml:"short_db"`
  36. Common common `toml:"common"`
  37. }
  38. var Conf config
  39. var Version string
  40. func MustParseConfig(configFile string) {
  41. if fileInfo, err := os.Stat(configFile); err != nil {
  42. if os.IsNotExist(err) {
  43. log.Panicf("configuration file %v does not exist.", configFile)
  44. } else {
  45. log.Panicf("configuration file %v can not be stated. %v", configFile, err)
  46. }
  47. } else {
  48. if fileInfo.IsDir() {
  49. log.Panicf("%v is a directory name", configFile)
  50. }
  51. }
  52. content, err := ioutil.ReadFile(configFile)
  53. if err != nil {
  54. log.Panicf("read configuration file error. %v", err)
  55. }
  56. content = bytes.TrimSpace(content)
  57. err = toml.Unmarshal(content, &Conf)
  58. if err != nil {
  59. log.Panicf("unmarshal toml object error. %v", err)
  60. }
  61. // short url black list
  62. Conf.Common.BlackShortURLsMap = make(map[string]bool)
  63. for _, blackShortURL := range Conf.Common.BlackShortURLs {
  64. Conf.Common.BlackShortURLsMap[blackShortURL] = true
  65. }
  66. // base string
  67. Conf.Common.BaseStringLength = uint64(len(Conf.Common.BaseString))
  68. }
  69. func init() {
  70. runtime.GOMAXPROCS(runtime.NumCPU())
  71. log.SetFlags(log.LstdFlags | log.Lshortfile)
  72. }