| 44 | ) |
| 45 | |
| 46 | func NewPostgres(conf *PostgresConfig, log kite.Logger) *Postgres { |
| 47 | if conf == nil { |
| 48 | conf = new(PostgresConfig) |
| 49 | |
| 50 | envLoader := &multiconfig.EnvironmentLoader{Prefix: "kontrol_postgres"} |
| 51 | configLoader := multiconfig.MultiLoader( |
| 52 | &multiconfig.TagLoader{}, envLoader, |
| 53 | ) |
| 54 | |
| 55 | if err := configLoader.Load(conf); err != nil { |
| 56 | fmt.Println("Valid environment variables are: ") |
| 57 | envLoader.PrintEnvs(conf) |
| 58 | panic(err) |
| 59 | } |
| 60 | |
| 61 | err := multiconfig.MultiValidator(&multiconfig.RequiredValidator{}).Validate(conf) |
| 62 | if err != nil { |
| 63 | fmt.Println("Valid environment variables are: ") |
| 64 | envLoader.PrintEnvs(conf) |
| 65 | panic(err) |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | connString := fmt.Sprintf( |
| 70 | "host=%s port=%d dbname=%s user=%s password=%s sslmode=disable connect_timeout=%d", |
| 71 | conf.Host, conf.Port, conf.DBName, conf.Username, conf.Password, conf.ConnectTimeout, |
| 72 | ) |
| 73 | |
| 74 | db, err := sql.Open("postgres", connString) |
| 75 | if err != nil { |
| 76 | panic(err) |
| 77 | } |
| 78 | |
| 79 | p := &Postgres{ |
| 80 | DB: db, |
| 81 | Log: log, |
| 82 | } |
| 83 | |
| 84 | cleanInterval := 120 * time.Second // clean every 120 second |
| 85 | go p.RunCleaner(cleanInterval, KeyTTL) |
| 86 | |
| 87 | return p |
| 88 | } |
| 89 | |
| 90 | // RunCleaner deletes every "interval" duration rows which are older than |
| 91 | // "expire" duration based on the "updated_at" field. For more info check |