Skip to content

Commit

Permalink
refactor api Start
Browse files Browse the repository at this point in the history
  • Loading branch information
tcarreira authored and wpjunior committed May 16, 2022
1 parent 9196e4d commit ccbdc24
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 7 deletions.
2 changes: 1 addition & 1 deletion cmd/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func main() {
}
}

a, err := web.NewWithTargetFactory(targetFactory)
a, err := web.NewWithTargetFactoryWithDefaults(targetFactory)
if err != nil {
log.Fatalf("could not create RPaaS API: %v", err)
}
Expand Down
48 changes: 42 additions & 6 deletions pkg/web/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package web
import (
"context"
"fmt"
"io"
"net/http"
"os"
"os/signal"
Expand Down Expand Up @@ -45,19 +46,27 @@ type api struct {
shutdown chan struct{}
}

type APIServerStartOptions struct {
DiscardLogging bool
}

// New creates an api instance.
func NewWithManager(manager rpaas.RpaasManager) (*api, error) {
localTargetFatory := target.NewLocalFactory(manager)
return NewWithTargetFactory(localTargetFatory)
return NewWithTargetFactoryWithDefaults(localTargetFatory)
}

func NewWithTargetFactoryWithDefaults(targetFactory target.Factory) (*api, error) {
return NewWithTargetFactory(targetFactory, `:9999`, `9993`, 30*time.Second, make(chan struct{}))
}

func NewWithTargetFactory(targetFactory target.Factory) (*api, error) {
func NewWithTargetFactory(targetFactory target.Factory, address, addressTLS string, shutdownTimeout time.Duration, shutdownChan chan struct{}) (*api, error) {
return &api{
Address: `:9999`,
TLSAddress: `:9993`,
ShutdownTimeout: 30 * time.Second,
Address: address,
TLSAddress: addressTLS,
ShutdownTimeout: shutdownTimeout,
e: newEcho(targetFactory),
shutdown: make(chan struct{}),
shutdown: shutdownChan,
}, nil
}

Expand All @@ -84,6 +93,33 @@ func (a *api) Start() error {
return nil
}

func (a *api) StartWithOptions(options APIServerStartOptions) error {
a.Lock()
a.started = true
a.Unlock()
go a.handleSignals()
if err := a.startServerWithOptions(options); err != http.ErrServerClosed {
fmt.Printf("problem to start the webserver: %+v", err)
return err
}
fmt.Println("Shutting down the webserver...")
return nil
}

func (a *api) startServerWithOptions(options APIServerStartOptions) error {
conf := config.Get()

if options.DiscardLogging {
a.e.Logger.SetOutput(io.Discard)
}

if conf.TLSCertificate != "" && conf.TLSKey != "" {
return a.e.StartTLS(a.TLSAddress, conf.TLSCertificate, conf.TLSKey)
}

return a.e.StartH2CServer(a.Address, &http2.Server{})
}

// Stop shut down the web server.
func (a *api) Stop() error {
a.Lock()
Expand Down

0 comments on commit ccbdc24

Please sign in to comment.