Skip to content

Commit a8f9998

Browse files
authored
feat: added shutdown method to be able to gracefully shut down the server (#51)
1 parent 5261687 commit a8f9998

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

kid.go

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package kid
22

33
import (
4+
"context"
45
"fmt"
56
"io"
67
"net/http"
@@ -28,6 +29,8 @@ type (
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.

kid_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package kid
22

33
import (
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+
449464
func TestKid_Static(t *testing.T) {
450465
k := New()
451466

0 commit comments

Comments
 (0)