yosai-server.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package main
  2. import (
  3. "database/sql"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "os"
  8. "git.aetherial.dev/aeth/yosai/pkg/config"
  9. configserver "git.aetherial.dev/aeth/yosai/pkg/config-server"
  10. "github.com/joho/godotenv"
  11. _ "github.com/lib/pq"
  12. )
  13. func main() {
  14. envFile := flag.String("env", "", "pass this to read an env file")
  15. username := flag.String("username", "", "The username to seed the db with, only has affect when calling with the --seed flag")
  16. dbSeed := flag.String("seed", "", "Pass this to seed the database with a configuration file")
  17. flag.Parse()
  18. if *envFile == "" {
  19. fmt.Println("No env file passed, attempting to run with raw environment")
  20. } else {
  21. err := godotenv.Load(*envFile)
  22. if err != nil {
  23. log.Fatal("Couldnt load the env file: ", err.Error())
  24. }
  25. }
  26. dbhost := os.Getenv("DB_HOST")
  27. dbuser := os.Getenv("DB_USER")
  28. dbpassword := os.Getenv("DB_PASS")
  29. dbname := "postgres"
  30. connectionString := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable", dbuser, dbpassword, dbhost, dbname)
  31. fmt.Print(connectionString)
  32. db, err := sql.Open("postgres", connectionString)
  33. if err != nil {
  34. log.Fatal(err)
  35. }
  36. defer db.Close()
  37. err = db.Ping()
  38. if err != nil {
  39. panic(err)
  40. }
  41. fmt.Println("Successfully connected!")
  42. configServerDb := configserver.NewSQLiteRepo(db, os.Stdout)
  43. configServerDb.Migrate()
  44. if *dbSeed != "" {
  45. if *username == "" {
  46. log.Fatal("Blank username not accepted. Use the --username flag to pass in a username to seed the database with")
  47. }
  48. conf := config.NewConfiguration(os.Stdout, config.ValidateUsername(*username))
  49. config.NewConfigHostImpl("./.config.json").Propogate(conf)
  50. user, err := configServerDb.AddUser(config.ValidateUsername(*username))
  51. if err != nil {
  52. log.Fatal(err.Error(), "failed to add user")
  53. }
  54. configServerDb.SeedUser(user, *conf)
  55. fmt.Println("Database created and seeded.")
  56. }
  57. configserver.RunHttpServer(8080, configServerDb, os.Stdout)
  58. }