Skip to content

Commit

Permalink
refactor: Encapsulate health check server logic (#46)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivov authored Dec 2, 2024
1 parent 3751567 commit a71cd1c
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 16 deletions.
15 changes: 1 addition & 14 deletions cmd/launcher/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package main
import (
"flag"
"fmt"
"net"
"os"

"task-runner-launcher/internal/commands"
Expand Down Expand Up @@ -40,19 +39,7 @@ func main() {
errorreporting.Init(cfg.Sentry)
defer errorreporting.Close()

srv := http.NewHealthCheckServer(cfg.HealthCheckServerPort)
go func() {
if err := srv.ListenAndServe(); err != nil {
errMsg := "Health check server failed to start"
if opErr, ok := err.(*net.OpError); ok && opErr.Op == "listen" {
errMsg = fmt.Sprintf("%s: Port %s is already in use", errMsg, srv.Addr)
} else {
errMsg = fmt.Sprintf("%s: %s", errMsg, err)
}
logs.Error(errMsg)
}
logs.Infof("Started launcher's health check server at port %d", srv.Addr)
}()
http.InitHealthCheckServer(cfg.HealthCheckServerPort)

cmd := &commands.LaunchCommand{}

Expand Down
22 changes: 21 additions & 1 deletion internal/http/healthcheck_server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package http
import (
"encoding/json"
"fmt"
"net"
"net/http"
"task-runner-launcher/internal/logs"
"time"
Expand All @@ -14,7 +15,26 @@ const (
writeTimeout = 1 * time.Second
)

func NewHealthCheckServer(port string) *http.Server {
// InitHealthCheckServer creates and starts the launcher's health check server
// exposing `/healthz` at the given port, running in a goroutine.
func InitHealthCheckServer(port string) {
srv := newHealthCheckServer(port)
go func() {
logs.Infof("Starting launcher's health check server at port %s", port)
if err := srv.ListenAndServe(); err != nil {
errMsg := "Health check server failed to start"
if opErr, ok := err.(*net.OpError); ok && opErr.Op == "listen" {
errMsg = fmt.Sprintf("%s: Port %s is already in use", errMsg, srv.Addr)
} else {
errMsg = fmt.Sprintf("%s: %s", errMsg, err)
}
logs.Error(errMsg)
return
}
}()
}

func newHealthCheckServer(port string) *http.Server {
mux := http.NewServeMux()
mux.HandleFunc(healthCheckPath, handleHealthCheck)

Expand Down
2 changes: 1 addition & 1 deletion internal/http/healthcheck_server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ func (w *failingWriter) WriteHeader(statusCode int) {
}

func TestNewHealthCheckServer(t *testing.T) {
server := NewHealthCheckServer("5680")
server := newHealthCheckServer("5680")

require.NotNil(t, server, "server should not be nil")

Expand Down

0 comments on commit a71cd1c

Please sign in to comment.