home » torr/wssrv.git
ID: b5d985f7d04303ccad087c58b60d2d93d14b77c7
51 lines — 1K — View raw


package ws

import (
	"fmt"
	"io"
	"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")
	}
	if err := checkFile(fileNa); err != nil {
		return err
	}

	return sendFileReply(con, fileNa)
}