config.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package main
  2. import (
  3. "encoding/hex"
  4. "flag"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "path/filepath"
  9. "gopkg.in/yaml.v2"
  10. )
  11. type config struct {
  12. Bind string
  13. ReadTimeout int `yaml:"read_timeout"`
  14. WriteTimeout int `yaml:"write_timeout"`
  15. Key string
  16. Salt string
  17. KeyBin []byte
  18. SaltBin []byte
  19. MaxSrcDimension int `yaml:"max_src_dimension"`
  20. Quality int
  21. Compression int
  22. }
  23. var conf = config{
  24. Bind: ":8080",
  25. MaxSrcDimension: 4096,
  26. }
  27. func absPathToFile(path string) string {
  28. if filepath.IsAbs(path) {
  29. return path
  30. }
  31. appPath, _ := filepath.Abs(filepath.Dir(os.Args[0]))
  32. return filepath.Join(appPath, path)
  33. }
  34. func init() {
  35. cpath := flag.String(
  36. "config", "../config.yml", "path to configuration file",
  37. )
  38. flag.Parse()
  39. file, err := os.Open(absPathToFile(*cpath))
  40. if err != nil {
  41. log.Fatalln(err)
  42. }
  43. defer file.Close()
  44. cdata, err := ioutil.ReadAll(file)
  45. if err != nil {
  46. log.Fatalln(err)
  47. }
  48. err = yaml.Unmarshal(cdata, &conf)
  49. if err != nil {
  50. log.Fatalln(err)
  51. }
  52. if len(conf.Bind) == 0 {
  53. conf.Bind = ":8080"
  54. }
  55. if conf.MaxSrcDimension == 0 {
  56. conf.MaxSrcDimension = 4096
  57. }
  58. if conf.KeyBin, err = hex.DecodeString(conf.Key); err != nil {
  59. log.Fatalln("Invalid key. Key should be encoded to hex")
  60. }
  61. if conf.SaltBin, err = hex.DecodeString(conf.Salt); err != nil {
  62. log.Fatalln("Invalid salt. Salt should be encoded to hex")
  63. }
  64. if conf.MaxSrcDimension == 0 {
  65. conf.MaxSrcDimension = 4096
  66. }
  67. if conf.Quality == 0 {
  68. conf.Quality = 80
  69. }
  70. if conf.Compression == 0 {
  71. conf.Compression = 6
  72. }
  73. }