diff --git a/internal/server/server.go b/internal/server/server.go index c6b2665..14b6913 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -29,16 +29,41 @@ type Server struct { addr string } -func New(fs *embed.FS, bs *booking.Service, ps *pdf.PdfService, hc *config.Host) *Server { +type options struct { + port *int +} + +type Option func(*options) error + +func WithPort(port int) Option { + return func(o *options) error { + if port <= 0 { + return errors.New("port should be positive") + } + o.port = &port + return nil + } +} + +func New(fs *embed.FS, bs *booking.Service, ps *pdf.PdfService, hc *config.Host, opts ...Option) (*Server, error) { + option := new(options) + for _, opt := range opts { + err := opt(option) + if err != nil { + return nil, err + } + } + s := &Server{ Router: NewRouter(*fs), bs: bs, ps: ps, hc: hc, - addr: fmt.Sprintf("0.0.0.0:%s", os.Getenv("PORT")), + addr: fmt.Sprintf("0.0.0.0:%d", *option.port), } + s.MountHandlers() - return s + return s, nil } func (s Server) Start() { diff --git a/main.go b/main.go index 2c41134..8858352 100644 --- a/main.go +++ b/main.go @@ -4,6 +4,7 @@ import ( "embed" "log" "os" + "strconv" "github.com/joho/godotenv" "gorm.io/driver/postgres" @@ -43,5 +44,14 @@ func main() { log.Fatal(err) } - server.New(&static, booking.NewService(db), ps, config.NewHost()).Start() + p := os.Getenv("PORT") + port, err := strconv.Atoi(p) + if err != nil { + log.Fatal(err) + } + srv, err := server.New(&static, booking.NewService(db), ps, config.NewHost(), server.WithPort(port)) + if err != nil { + log.Fatal(err) + } + srv.Start() }