home » torr/wssrv.git
Author C. Torres <torr.c@mailgw.com> 2024-12-16 00:52:36
Committer C. Torres <torr.c@mailgw.com> 2024-12-16 00:52:36
Commit 937e0f3 (patch)
Tree 440b21d
Parent(s)

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 <torr.c@mailgw.com>


commits diff: 7770d0d..937e0f3
1 file changed, 63 insertions, 0 deletionsdownload


Diffstat
-rw-r--r-- ws/file_reply.go 63

Diff options
View
Side
Whitespace
Context lines
Inter-hunk lines
+63/-0 A   ws/file_reply.go
index 0000000..e76cc71
old size: 0B - new size: 1K
new file mode: -rw-r--r--
@@ -0,0 +1,63 @@
1 + package ws
2 +
3 + import (
4 + "fmt"
5 + "io"
6 + "io/fs"
7 + "os"
8 + "wssrv/log"
9 +
10 + "github.com/gorilla/websocket"
11 + )
12 +
13 + func sendFileReply(con *websocket.Conn, fileNa string) error {
14 + var (
15 + err error
16 + msg, data []byte
17 + )
18 +
19 + if data, err = os.ReadFile(fileNa); err != nil {
20 + return fmt.Errorf("unable to read file '%s': %v", fileNa, err)
21 + }
22 +
23 + for err != io.EOF {
24 + if _, msg, err = con.ReadMessage(); err != nil {
25 + return fmt.Errorf("unable to read from websocket on '%s': %v", con.RemoteAddr(), err)
26 + }
27 + fmt.Printf("(%s): %s\n", con.RemoteAddr(), msg)
28 +
29 + log.Info.Printf("sending file '%s'", fileNa)
30 + if err = con.WriteMessage(websocket.TextMessage, data); err != nil {
31 + return fmt.Errorf("unable write on websocket on '%s': %v", con.RemoteAddr(), err)
32 + }
33 + }
34 +
35 + return nil
36 + }
37 +
38 + // SendFileReply sends a given file in the websocket as a reply to every
39 + // message received.
40 + func SendFileReply(con *websocket.Conn, fileNa string) error {
41 + switch {
42 + case con == nil:
43 + return fmt.Errorf("nil connection parameter")
44 + case len(fileNa) == 0:
45 + return fmt.Errorf("empty file parameter")
46 + }
47 + var (
48 + err error
49 + stat fs.FileInfo
50 + )
51 +
52 + if stat, err = os.Stat(fileNa); err != nil {
53 + return fmt.Errorf("unable to check metadata for file '%s': %v", fileNa, err)
54 + }
55 + if !stat.Mode().IsRegular() {
56 + return fmt.Errorf("file '%s' is not regular")
57 + }
58 + if stat.Mode()&0444 == 0 {
59 + return fmt.Errorf("file '%s' is not readable")
60 + }
61 +
62 + return sendFileReply(con, fileNa)
63 + }