From 937e0f30e601f935339beb29f067de0cff431b09 Mon Sep 17 00:00:00 2001 From: "C. Torres" Date: Sun, 15 Dec 2024 21:52:36 -0300 Subject: [PATCH] Implement file reply serving mode Implement a serving mode where a file is sent as reply to every websocket message received. Signed-off-by: C. Torres --- ws/file_reply.go | 63 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 ws/file_reply.go diff --git a/ws/file_reply.go b/ws/file_reply.go new file mode 100644 index 0000000..e76cc71 --- /dev/null +++ b/ws/file_reply.go @@ -0,0 +1,63 @@ +package ws + +import ( + "fmt" + "io" + "io/fs" + "os" + "wssrv/log" + + "github.com/gorilla/websocket" +) + +func sendFileReply(con *websocket.Conn, fileNa string) error { + var ( + err error + msg, data []byte + ) + + if data, err = os.ReadFile(fileNa); err != nil { + return fmt.Errorf("unable to read file '%s': %v", fileNa, err) + } + + for err != io.EOF { + if _, msg, err = con.ReadMessage(); err != nil { + return fmt.Errorf("unable to read from websocket on '%s': %v", con.RemoteAddr(), err) + } + fmt.Printf("(%s): %s\n", con.RemoteAddr(), msg) + + log.Info.Printf("sending file '%s'", fileNa) + if err = con.WriteMessage(websocket.TextMessage, data); err != nil { + return fmt.Errorf("unable write on websocket on '%s': %v", con.RemoteAddr(), err) + } + } + + return nil +} + +// SendFileReply sends a given file in the websocket as a reply to every +// message received. +func SendFileReply(con *websocket.Conn, fileNa string) error { + switch { + case con == nil: + return fmt.Errorf("nil connection parameter") + case len(fileNa) == 0: + return fmt.Errorf("empty file parameter") + } + var ( + err error + stat fs.FileInfo + ) + + if stat, err = os.Stat(fileNa); err != nil { + return fmt.Errorf("unable to check metadata for file '%s': %v", fileNa, err) + } + if !stat.Mode().IsRegular() { + return fmt.Errorf("file '%s' is not regular") + } + if stat.Mode()&0444 == 0 { + return fmt.Errorf("file '%s' is not readable") + } + + return sendFileReply(con, fileNa) +}