mirror of
https://github.com/rjNemo/rentease.git
synced 2026-06-11 05:06:52 +00:00
func opt pattern
This commit is contained in:
parent
a7514e9419
commit
3078bac637
2 changed files with 39 additions and 4 deletions
|
|
@ -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
12
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()
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue