You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.7 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "net"
  7. "os"
  8. "git.chrishayward.xyz/x/users/proto"
  9. "git.chrishayward.xyz/x/users/server"
  10. "google.golang.org/grpc"
  11. "gopkg.in/yaml.v3"
  12. "gorm.io/driver/postgres"
  13. "gorm.io/driver/sqlite"
  14. "gorm.io/gorm"
  15. )
  16. var configPath = flag.String("config", "./config/server.yaml", "--config=./config/server.yaml")
  17. type config struct {
  18. Port int `yaml:"port"`
  19. Secret string `yaml:"secret"`
  20. Database struct {
  21. Type string `yaml:"type"`
  22. File string `yaml:"file"`
  23. Host string `yaml:"host"`
  24. Port int `yaml:"port"`
  25. Name string `yaml:"name"`
  26. User string `yaml:"user"`
  27. Password string `yaml:"password"`
  28. } `yaml:"database"`
  29. }
  30. func main() {
  31. // Parse the optional flags.
  32. flag.Parse()
  33. // Read the config file.
  34. config := &config{}
  35. file, err := os.Open(*configPath)
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. defer file.Close()
  40. if err := yaml.NewDecoder(file).Decode(&config); err != nil {
  41. log.Fatal(err)
  42. }
  43. // Initialize the database.
  44. var db *gorm.DB
  45. switch config.Database.Type {
  46. case "postgres":
  47. db, _ = gorm.Open(postgres.Open(fmt.Sprintf(
  48. "host=%s user=%s password=%s dbname=%s port=%d sslmode=disable",
  49. config.Database.Host,
  50. config.Database.User,
  51. config.Database.Password,
  52. config.Database.Name,
  53. config.Database.Port)))
  54. case "sqlite":
  55. default:
  56. db, _ = gorm.Open(sqlite.Open(config.Database.File), &gorm.Config{})
  57. }
  58. // Create the network listener.
  59. lis, err := net.Listen("tcp", fmt.Sprintf(":%d", config.Port))
  60. if err != nil {
  61. log.Fatal(err)
  62. }
  63. // Start listening for requests.
  64. srv := grpc.NewServer()
  65. proto.RegisterUsersServer(srv, server.NewUsersServer(&config.Secret, db))
  66. log.Printf("Listening on :%d", config.Port)
  67. srv.Serve(lis)
  68. }