Skip to content

Commit a227516

Browse files
Add health server implementation using health_port config (#392)
1 parent 2211bf2 commit a227516

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

pkg/service/service.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ type Service struct {
5353

5454
promServer *http.Server
5555
pprofServer *http.Server
56+
healthServer *http.Server
5657
rpcSIPServer rpc.SIPInternalServer
5758

5859
sipServiceStop sipServiceStopFunc
@@ -98,6 +99,29 @@ func NewService(
9899
Handler: mux,
99100
}
100101
}
102+
if conf.HealthPort > 0 {
103+
mux := http.NewServeMux()
104+
s.healthServer = &http.Server{
105+
Addr: fmt.Sprintf(":%d", conf.HealthPort),
106+
Handler: mux,
107+
}
108+
109+
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
110+
st := s.Health()
111+
var code int
112+
switch st {
113+
case stats.HealthOK:
114+
code = http.StatusOK
115+
case stats.HealthUnderLoad:
116+
code = http.StatusTooManyRequests
117+
default:
118+
code = http.StatusServiceUnavailable
119+
}
120+
w.Header().Set("Content-Type", "text/plain")
121+
w.WriteHeader(code)
122+
_, _ = w.Write([]byte(st.String()))
123+
})
124+
}
101125
return s
102126
}
103127

@@ -132,6 +156,17 @@ func (s *Service) Run() error {
132156
}()
133157
}
134158

159+
if srv := s.healthServer; srv != nil {
160+
l, err := net.Listen("tcp", srv.Addr)
161+
if err != nil {
162+
return err
163+
}
164+
defer l.Close()
165+
go func() {
166+
_ = srv.Serve(l)
167+
}()
168+
}
169+
135170
var err error
136171
if s.rpcSIPServer, err = rpc.NewSIPInternalServer(s.psrpcServer, s.bus); err != nil {
137172
return err

0 commit comments

Comments
 (0)