Skip to content

Commit 74fceda

Browse files
committed
feat(http): add listen method to http server
1 parent 91de0b6 commit 74fceda

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

http/server.go

+31
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
package http
22

33
import (
4+
"context"
5+
"errors"
46
"net/http"
7+
"os"
8+
"os/signal"
9+
"syscall"
510
"time"
611

712
"github.com/gorilla/mux"
@@ -43,3 +48,29 @@ func WithRoute(method, path string, handler http.Handler) Option {
4348
s.router.Methods(method).Path(path).Handler(handler)
4449
}
4550
}
51+
52+
// Listen runs the server in a blocking way. In returns either if an error occur which in that case returns the error,
53+
// or if the server is stopped by a signal (i.e. `SIGINT` or `SIGTERM`).
54+
func (s *Server) Listen() error {
55+
listenErr := make(chan error, 1)
56+
go func() {
57+
listenErr <- s.server.ListenAndServe()
58+
}()
59+
60+
kill := make(chan os.Signal, 1)
61+
signal.Notify(kill, syscall.SIGINT, syscall.SIGTERM)
62+
63+
for {
64+
select {
65+
case err := <-listenErr:
66+
if errors.Is(err, http.ErrServerClosed) {
67+
return nil
68+
}
69+
return err
70+
case <-kill:
71+
if err := s.server.Shutdown(context.Background()); err != nil {
72+
return err
73+
}
74+
}
75+
}
76+
}

0 commit comments

Comments
 (0)