config.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "flag"
  6. "io/ioutil"
  7. "log"
  8. "os"
  9. "strconv"
  10. )
  11. func intEnvConfig(i *int, name string) {
  12. if env, err := strconv.Atoi(os.Getenv(name)); err == nil {
  13. *i = env
  14. }
  15. }
  16. func strEnvConfig(s *string, name string) {
  17. if env := os.Getenv(name); len(env) > 0 {
  18. *s = env
  19. }
  20. }
  21. func hexEnvConfig(b *[]byte, name string) {
  22. var err error
  23. if env := os.Getenv(name); len(env) > 0 {
  24. if *b, err = hex.DecodeString(env); err != nil {
  25. log.Fatalf("%s expected to be hex-encoded string\n", name)
  26. }
  27. }
  28. }
  29. func hexFileConfig(b *[]byte, filepath string) {
  30. if len(filepath) == 0 {
  31. return
  32. }
  33. f, err := os.Open(filepath)
  34. if err != nil {
  35. log.Fatalf("Can't open file %s\n", filepath)
  36. }
  37. src, err := ioutil.ReadAll(f)
  38. if err != nil {
  39. log.Fatalln(err)
  40. }
  41. src = bytes.TrimSpace(src)
  42. dst := make([]byte, hex.DecodedLen(len(src)))
  43. n, err := hex.Decode(dst, src)
  44. if err != nil {
  45. log.Fatalf("%s expected to contain hex-encoded string\n", filepath)
  46. }
  47. *b = dst[:n]
  48. }
  49. type config struct {
  50. Bind string
  51. ReadTimeout int
  52. WriteTimeout int
  53. MaxSrcDimension int
  54. Quality int
  55. Compression int
  56. GZipCompression int
  57. Key []byte
  58. Salt []byte
  59. }
  60. var conf = config{
  61. Bind: ":8080",
  62. ReadTimeout: 10,
  63. WriteTimeout: 10,
  64. MaxSrcDimension: 4096,
  65. Quality: 80,
  66. Compression: 6,
  67. GZipCompression: 5,
  68. }
  69. func init() {
  70. keypath := flag.String("keypath", "", "path of the file with hex-encoded key")
  71. saltpath := flag.String("saltpath", "", "path of the file with hex-encoded salt")
  72. flag.Parse()
  73. strEnvConfig(&conf.Bind, "IMGPROXY_BIND")
  74. intEnvConfig(&conf.ReadTimeout, "IMGPROXY_READ_TIMEOUT")
  75. intEnvConfig(&conf.WriteTimeout, "IMGPROXY_WRITE_TIMEOUT")
  76. intEnvConfig(&conf.MaxSrcDimension, "IMGPROXY_MAX_SRC_DIMENSION")
  77. intEnvConfig(&conf.Quality, "IMGPROXY_QUALITY")
  78. intEnvConfig(&conf.Compression, "IMGPROXY_COMPRESSION")
  79. intEnvConfig(&conf.GZipCompression, "IMGPROXY_GZIP_COMPRESSION")
  80. hexEnvConfig(&conf.Key, "IMGPROXY_KEY")
  81. hexEnvConfig(&conf.Salt, "IMGPROXY_SALT")
  82. hexFileConfig(&conf.Key, *keypath)
  83. hexFileConfig(&conf.Salt, *saltpath)
  84. if len(conf.Key) == 0 {
  85. log.Fatalln("Key is not defined")
  86. }
  87. if len(conf.Salt) == 0 {
  88. log.Fatalln("Salt is not defined")
  89. }
  90. }