Skip to content

Commit

Permalink
Handle connection closing and utilities interruption correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
slytomcat committed Apr 22, 2024
1 parent d7df728 commit c982f15
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
9 changes: 7 additions & 2 deletions connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"os/signal"
"strings"
"sync"
"syscall"
"time"

"github.com/chzyer/readline"
Expand Down Expand Up @@ -123,7 +124,7 @@ func connect(url string, rlConf *readline.Config) []error {
}
go func() {
sig := make(chan os.Signal, 2)
signal.Notify(sig, os.Interrupt, os.Kill)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
fmt.Printf("\n%s signal received, exiting...\n", <-sig)
rl.Close()
session.cancel()
Expand Down Expand Up @@ -190,7 +191,11 @@ func (s *Session) readWebsocket() {
for {
msgType, buf, err := s.ws.ReadMessage()
if err != nil {
s.setErr(fmt.Errorf("reading error: `%w`", err))
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseNormalClosure, websocket.CloseServiceRestart) {
s.setErr(fmt.Errorf("reading error: `%v`", err))
} else {
s.setErr(fmt.Errorf("connection closed: %s", err))
}
return
}
var text string
Expand Down
3 changes: 2 additions & 1 deletion echo-server/echo-server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"os/signal"
"strings"
"syscall"

"github.com/gorilla/websocket"
"github.com/slytomcat/ws/server"
Expand Down Expand Up @@ -74,7 +75,7 @@ func main() {
})
go func() {
sig := make(chan os.Signal, 2)
signal.Notify(sig, os.Interrupt, os.Kill)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
fmt.Printf("\n%s signal received, exiting...\n", <-sig)
srv.Close()
}()
Expand Down

0 comments on commit c982f15

Please sign in to comment.