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) +}