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 1
1
package kid
2
2
3
3
import (
4
+ "context"
4
5
"fmt"
5
6
"io"
6
7
"net/http"
28
29
//
29
30
// It's a framework instance.
30
31
Kid struct {
32
+ server * http.Server
33
+ mutex sync.Mutex
31
34
router Tree
32
35
middlewares []MiddlewareFunc
33
36
notFoundHandler HandlerFunc
@@ -61,6 +64,7 @@ func New() *Kid {
61
64
xmlSerializer : serializer .NewXMLSerializer (),
62
65
htmlRenderer : htmlrenderer .Default (false ),
63
66
debug : true ,
67
+ mutex : sync.Mutex {},
64
68
}
65
69
66
70
kid .pool .New = func () any {
@@ -80,7 +84,19 @@ func (k *Kid) Run(address ...string) error {
80
84
k .printDebug (os .Stdout , "Starting server at %s\n " , addr )
81
85
k .printDebug (os .Stdout , "Quit the server with CONTROL-C\n " )
82
86
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 )
84
100
}
85
101
86
102
// 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
2
2
3
3
import (
4
4
"bytes"
5
+ "context"
5
6
"fmt"
6
7
"io"
7
8
"net/http"
@@ -446,6 +447,20 @@ func TestKid_Run(t *testing.T) {
446
447
assert .Equal (t , "{\" message\" :\" healthy\" }\n " , string (body ))
447
448
}
448
449
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
+
449
464
func TestKid_Static (t * testing.T ) {
450
465
k := New ()
451
466
You can’t perform that action at this time.
0 commit comments