@@ -6,12 +6,11 @@ import (
6
6
"errors"
7
7
"fmt"
8
8
"net/http"
9
+ "strings"
9
10
"sync"
10
11
"sync/atomic"
11
12
"time"
12
13
13
- "github.com/go-chi/chi/v5"
14
- chimiddleware "github.com/go-chi/chi/v5/middleware"
15
14
"google.golang.org/protobuf/encoding/protojson"
16
15
17
16
"github.com/schigh/health"
@@ -48,23 +47,34 @@ func NewReporter(cfg Config) *Reporter {
48
47
reporter .logger = health.NoOpLogger {}
49
48
}
50
49
51
- router := chi .NewRouter ()
52
- router .Use (chimiddleware .Recoverer )
53
- router .Use (chimiddleware .Timeout (60 * time .Second ))
54
- router .Route ("/health" , func (r chi.Router ) {
55
- r .Get (cfg .LivenessRoute , reporter .reportLiveness )
56
- r .Get (cfg .ReadinessRoute , reporter .reportReadiness )
57
- })
50
+ mux := http .NewServeMux ()
51
+ mux .HandleFunc (fmt .Sprintf ("/health/%s" , strings .TrimPrefix (cfg .LivenessRoute , "/" )), reporter .reportLiveness )
52
+ mux .HandleFunc (fmt .Sprintf ("/health/%s" , strings .TrimPrefix (cfg .ReadinessRoute , "/" )), reporter .reportReadiness )
53
+ handler := reporter .Recover (
54
+ http .TimeoutHandler (mux , 60 * time .Second , "the request timed out" ),
55
+ )
58
56
59
57
reporter .server = & http.Server {
60
58
ReadHeaderTimeout : 3 * time .Second ,
61
59
Addr : fmt .Sprintf ("%s:%d" , cfg .Addr , cfg .Port ),
62
- Handler : router ,
60
+ Handler : handler ,
63
61
}
64
62
65
63
return & reporter
66
64
}
67
65
66
+ func (r * Reporter ) Recover (next http.Handler ) http.Handler {
67
+ return http .HandlerFunc (func (rw http.ResponseWriter , req * http.Request ) {
68
+ defer func () {
69
+ if recovered := recover (); recovered != nil {
70
+ r .logger .Error ("health.reporter.httpserver: recovered from panic: %v" , recovered )
71
+ http .Error (rw , http .StatusText (http .StatusServiceUnavailable ), http .StatusServiceUnavailable )
72
+ }
73
+ }()
74
+ next .ServeHTTP (rw , req )
75
+ })
76
+ }
77
+
68
78
func (r * Reporter ) Run (_ context.Context ) error {
69
79
if ! atomic .CompareAndSwapUint32 (& r .running , 0 , 1 ) {
70
80
return errors .New ("health.reporters.httpserver: Run - reporter is already running" )
0 commit comments