Skip to content

Commit

Permalink
refactor(port-handling): allocate port upon startup
Browse files Browse the repository at this point in the history
  • Loading branch information
pkkummermo committed Dec 18, 2023
1 parent d37b11b commit 6f85aad
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
"net"
"net/http"
"os"
"time"
Expand Down Expand Up @@ -229,6 +230,12 @@ func (server *App) Start(port ...uint16) error {
server.port = server.config.server.port
}

// Reserve port and buffer incoming connections
listener, listenerErr := net.Listen("tcp", fmt.Sprintf(":%d", server.port))
if listenerErr != nil {
return listenerErr
}

// Initialize all plugins
for _, plugin := range server.config.server.plugins {
slog.Debug(fmt.Sprintf("Plugins: Running Apply for '%s'", plugin.Name()))
Expand All @@ -239,7 +246,6 @@ func (server *App) Start(port ...uint16) error {

server.server = http.Server{
ReadHeaderTimeout: time.Second * time.Duration(server.config.server.maxReadTimeout),
Addr: fmt.Sprintf(":%d", server.port),
Handler: server.mux,
}

Expand All @@ -248,11 +254,11 @@ func (server *App) Start(port ...uint16) error {
slog.Info(fmt.Sprintf("Server can be accessed at http://localhost:%d", server.port))
}

if err := server.server.ListenAndServe(); err != nil {
if errors.Is(err, http.ErrServerClosed) {
if serveErr := server.server.Serve(listener); serveErr != nil {
if errors.Is(serveErr, http.ErrServerClosed) {
return nil
}
return err
return serveErr
}

return nil
Expand Down

0 comments on commit 6f85aad

Please sign in to comment.