File tree Expand file tree Collapse file tree 2 files changed +32
-1
lines changed
Expand file tree Collapse file tree 2 files changed +32
-1
lines changed Original file line number Diff line number Diff line change 11package kid
22
33import (
4+ "context"
45 "fmt"
56 "io"
67 "net/http"
2829 //
2930 // It's a framework instance.
3031 Kid struct {
32+ server * http.Server
33+ mutex sync.Mutex
3134 router Tree
3235 middlewares []MiddlewareFunc
3336 notFoundHandler HandlerFunc
@@ -61,6 +64,7 @@ func New() *Kid {
6164 xmlSerializer : serializer .NewXMLSerializer (),
6265 htmlRenderer : htmlrenderer .Default (false ),
6366 debug : true ,
67+ mutex : sync.Mutex {},
6468 }
6569
6670 kid .pool .New = func () any {
@@ -80,7 +84,19 @@ func (k *Kid) Run(address ...string) error {
8084 k .printDebug (os .Stdout , "Starting server at %s\n " , addr )
8185 k .printDebug (os .Stdout , "Quit the server with CONTROL-C\n " )
8286
83- return http .ListenAndServe (addr , k )
87+ k .mutex .Lock ()
88+ k .server = & http.Server {Addr : addr , Handler : k }
89+ k .mutex .Unlock ()
90+
91+ return k .server .ListenAndServe ()
92+ }
93+
94+ // Shutdown gracefully shuts down the server without interrupting any active connections.
95+ func (k * Kid ) Shutdown (ctx context.Context ) error {
96+ k .mutex .Lock ()
97+ defer k .mutex .Unlock ()
98+
99+ return k .server .Shutdown (ctx )
84100}
85101
86102// Use registers a new middleware. The middleware will be applied to all of the routes.
Original file line number Diff line number Diff line change @@ -2,6 +2,7 @@ package kid
22
33import (
44 "bytes"
5+ "context"
56 "fmt"
67 "io"
78 "net/http"
@@ -446,6 +447,20 @@ func TestKid_Run(t *testing.T) {
446447 assert .Equal (t , "{\" message\" :\" healthy\" }\n " , string (body ))
447448}
448449
450+ func TestKid_Shutdown (t * testing.T ) {
451+ k := New ()
452+
453+ go func () {
454+ err := k .Run (":8585" )
455+ assert .ErrorIs (t , err , http .ErrServerClosed )
456+ }()
457+
458+ // Wait for the server to start
459+ time .Sleep (5 * time .Millisecond )
460+
461+ assert .NoError (t , k .Shutdown (context .Background ()))
462+ }
463+
449464func TestKid_Static (t * testing.T ) {
450465 k := New ()
451466
You can’t perform that action at this time.
0 commit comments