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