mirror of
https://github.com/rjNemo/rentease.git
synced 2026-06-12 13:46:51 +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
|
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{
|
s := &Server{
|
||||||
Router: NewRouter(*fs),
|
Router: NewRouter(*fs),
|
||||||
bs: bs,
|
bs: bs,
|
||||||
ps: ps,
|
ps: ps,
|
||||||
hc: hc,
|
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()
|
s.MountHandlers()
|
||||||
return s
|
return s, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s Server) Start() {
|
func (s Server) Start() {
|
||||||
|
|
|
||||||
12
main.go
12
main.go
|
|
@ -4,6 +4,7 @@ import (
|
||||||
"embed"
|
"embed"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
"github.com/joho/godotenv"
|
"github.com/joho/godotenv"
|
||||||
"gorm.io/driver/postgres"
|
"gorm.io/driver/postgres"
|
||||||
|
|
@ -43,5 +44,14 @@ func main() {
|
||||||
log.Fatal(err)
|
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