fix: omit race condition

This commit is contained in:
franklin 2023-08-09 07:09:59 +02:00
parent e1aa3e0a1b
commit 7e2f6de992

View File

@ -5,6 +5,7 @@ import (
"net" "net"
"net/http" "net/http"
"strings" "strings"
"sync/atomic"
"github.com/pkg/errors" "github.com/pkg/errors"
"go.uber.org/zap" "go.uber.org/zap"
@ -15,7 +16,7 @@ import (
// ServiceHTTP struct // ServiceHTTP struct
type ServiceHTTP struct { type ServiceHTTP struct {
running bool running atomic.Bool
server *http.Server server *http.Server
name string name string
l *zap.Logger l *zap.Logger
@ -44,7 +45,7 @@ func (s *ServiceHTTP) Name() string {
} }
func (s *ServiceHTTP) Healthz() error { func (s *ServiceHTTP) Healthz() error {
if !s.running { if !s.running.Load() {
return ErrServiceNotRunning return ErrServiceNotRunning
} }
return nil return nil
@ -62,9 +63,9 @@ func (s *ServiceHTTP) Start(ctx context.Context) error {
s.l.Info("starting http service", fields...) s.l.Info("starting http service", fields...)
s.server.BaseContext = func(_ net.Listener) context.Context { return ctx } s.server.BaseContext = func(_ net.Listener) context.Context { return ctx }
s.server.RegisterOnShutdown(func() { s.server.RegisterOnShutdown(func() {
s.running = false s.running.Store(false)
}) })
s.running = true s.running.Store(true)
if err := s.server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) { if err := s.server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.WithError(s.l, err).Error("service error") log.WithError(s.l, err).Error("service error")
return err return err