Skip to content

Commit

Permalink
feat(http): add listen method to http server
Browse files Browse the repository at this point in the history
  • Loading branch information
amimart committed Sep 17, 2024
1 parent 91de0b6 commit 79d6bb3
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions http/server.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
package http

import (
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"

"github.com/gorilla/mux"
Expand Down Expand Up @@ -43,3 +47,30 @@ func WithRoute(method, path string, handler http.Handler) Option {
s.router.Methods(method).Path(path).Handler(handler)
}
}

// Listen serves the server's handler on the provided address in a blocking way. In returns either if an error occur
// which in that case returns the error, or if the server is stopped by a signal (i.e. `SIGINT` or `SIGTERM`).
// nolint:gosec

Check failure on line 53 in http/server.go

View workflow job for this annotation

GitHub Actions / lint-go

directive `// nolint:gosec` should be written without leading space as `//nolint:gosec` (nolintlint)
func (s *Server) Listen(addr string) error {
ln, err := net.Listen("tcp4", addr)
if err != nil {
return err

Check warning on line 57 in http/server.go

View check run for this annotation

Codecov / codecov/patch

http/server.go#L54-L57

Added lines #L54 - L57 were not covered by tests
}

listenErr := make(chan error, 1)
go func() {
listenErr <- http.Serve(ln, s.router)
}()

Check warning on line 63 in http/server.go

View check run for this annotation

Codecov / codecov/patch

http/server.go#L60-L63

Added lines #L60 - L63 were not covered by tests

kill := make(chan os.Signal, 1)
signal.Notify(kill, syscall.SIGINT, syscall.SIGTERM)

Check warning on line 66 in http/server.go

View check run for this annotation

Codecov / codecov/patch

http/server.go#L65-L66

Added lines #L65 - L66 were not covered by tests

for {
select {
case err := <-listenErr:
return err
case <-kill:
return ln.Close()

Check warning on line 73 in http/server.go

View check run for this annotation

Codecov / codecov/patch

http/server.go#L68-L73

Added lines #L68 - L73 were not covered by tests
}
}
}

0 comments on commit 79d6bb3

Please sign in to comment.