I am trying to capture signals like ctrl+c, ctrl+z, ctrl+\ in golang and write its equivalent hex code to websocket. I am doing something like below.
func (c *poc) writePump() {
var b = make([]byte, 1)
d := make(chan os.Signal, 1)
signal.Notify(d, syscall.SIGINT, syscall.SIGTSTP, syscall.SIGQUIT)
for {
os.Stdin.Read(b)
err = c.ws.WriteMessage(websocket.TextMessage, b)
go func() {
for {
s := <-d
err = cli.sendControlSignalToWebsockets(s)
}
}()
if err != nil {
log.Printf("Failed to send UTF8 char: %s", err)
}
}
}
func (c *poc) sendControlSignalToWebsockets(s os.Signal) error {
var err error
switch s {
case syscall.SIGINT:
err = c.ws.WriteMessage(websocket.TextMessage, []byte{'\003'})
case syscall.SIGTSTP:
err = c.ws.WriteMessage(websocket.TextMessage, []byte{'\x1a'})
case syscall.SIGQUIT:
err = c.ws.WriteMessage(websocket.TextMessage, []byte{'\x1c'})
}
if err != nil {
return err
}
return nil
}
Instead I want to do something like, capturing all signals and instead of hardcoding each signals equivalent to it's hexcode, convert signal to hexcode.
func (c *poc) writePump() {
var b = make([]byte, 1)
d := make(chan os.Signal, 1)
signal.Notify(d)
for {
os.Stdin.Read(b)
err = c.ws.WriteMessage(websocket.TextMessage, b)
go func() {
for {
s := <-d
//???? do some conversions and write it to websocket
}
}()
if err != nil {
log.Printf("Failed to send UTF8 char: %s", err)
}
}
}
Curious to know if anyone has any idea. Thanks!
It sounds like you're trying to communicate a signal over a websocket. And thus you need a way to encode it won't get confused with other characters so using the unprintable ascii characters is a reasonable move.
Since there is no convention for mapping syscall
signals into a byte
, you can't just import it - but good news! - you get to create your own!
Create a map[syscall.Signal]byte
or map[os.Signal]byte
and do the translation from there:
// Create a mapping between syscalls and bytes
var syscallByteMap = map[syscall.Signal]byte{
syscall.SIGINT: '\003',
...more here...
}
...truncated...
go func() {
for {
s := <-d
// Look up the signal in the map
b, ok := syscallByteMap[s]
if ok {
err = c.ws.WriteMessage(websocket.TextMessage, []byte{b})
} else {
err = nil
}
}
}()