func opt pattern

This commit is contained in:
Ruidy 2024-03-03 21:40:17 +01:00
parent a7514e9419
commit 3078bac637
No known key found for this signature in database
GPG key ID: E00F51288CB857CC
2 changed files with 39 additions and 4 deletions

View file

@ -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() {

12
main.go
View file

@ -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()
}