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.

80 lines
1.8 KiB

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