|
1 | 1 | package main |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "encoding/json" |
4 | 5 | "errors" |
5 | 6 | "fmt" |
| 7 | + "io/ioutil" |
| 8 | + "log" |
| 9 | + "os" |
| 10 | + |
| 11 | + "muzzammil.xyz/jsonc" |
6 | 12 | ) |
7 | 13 |
|
| 14 | +var customEnvFileVarName = "RTCV_SCRAPER_CLIENT_ENV_FILE" |
| 15 | +var envAsVarName = "RTCV_SCRAPER_CLIENT_ENV" |
| 16 | + |
| 17 | +func mustReadEnv() Env { |
| 18 | + envFilename := "env.json" |
| 19 | + alternativeFileName := os.Getenv(customEnvFileVarName) |
| 20 | + if alternativeFileName != "" { |
| 21 | + envFilename = alternativeFileName |
| 22 | + } |
| 23 | + |
| 24 | + notFoundErr := func() string { |
| 25 | + if alternativeFileName != "" { |
| 26 | + return "no " + alternativeFileName + " file or $" + envAsVarName + " environment variable found, cannot continue" |
| 27 | + } |
| 28 | + return "no env.json(c) file or $" + envAsVarName + " environment variable found, cannot continue" |
| 29 | + } |
| 30 | + |
| 31 | + envFileBytes, err := ioutil.ReadFile(envFilename) |
| 32 | + if err == nil { |
| 33 | + return mustParseEnv(envFileBytes) |
| 34 | + } |
| 35 | + |
| 36 | + envFileBytes = []byte(os.Getenv(envAsVarName)) |
| 37 | + if len(envFileBytes) != 0 { |
| 38 | + return mustParseEnv(envFileBytes) |
| 39 | + } |
| 40 | + |
| 41 | + if !os.IsNotExist(err) { |
| 42 | + log.Fatal("unable to read env file, error: " + err.Error()) |
| 43 | + } |
| 44 | + |
| 45 | + if alternativeFileName != "" { |
| 46 | + log.Fatalln(notFoundErr()) |
| 47 | + } |
| 48 | + |
| 49 | + envFilename = "env.jsonc" |
| 50 | + envFileBytes, err = ioutil.ReadFile(envFilename) |
| 51 | + if err != nil { |
| 52 | + log.Fatalln(notFoundErr()) |
| 53 | + } |
| 54 | + |
| 55 | + return mustParseEnv(envFileBytes) |
| 56 | +} |
| 57 | + |
| 58 | +func mustParseEnv(b []byte) Env { |
| 59 | + envJSON := jsonc.ToJSON(b) |
| 60 | + if !json.Valid(envJSON) { |
| 61 | + log.Fatal("env file is not valid json or jsonc") |
| 62 | + } |
| 63 | + |
| 64 | + env := Env{} |
| 65 | + err := json.Unmarshal(envJSON, &env) |
| 66 | + if err != nil { |
| 67 | + log.Fatal("unable to parse env file, error: " + err.Error()) |
| 68 | + } |
| 69 | + |
| 70 | + err = env.validate() |
| 71 | + if err != nil { |
| 72 | + log.Fatal("validating env failed, error: " + err.Error()) |
| 73 | + } |
| 74 | + |
| 75 | + return env |
| 76 | +} |
| 77 | + |
8 | 78 | // Env contains the structure of an env.json file |
9 | 79 | type Env struct { |
10 | 80 | PrivateKey string `json:"private_key"` |
|
0 commit comments