Skip to content

Instantly share code, notes, and snippets.

@dharanad
Created February 3, 2023 18:27
Show Gist options
  • Save dharanad/d54ddad2fc6ff1d897747c8d2af92bcd to your computer and use it in GitHub Desktop.
Save dharanad/d54ddad2fc6ff1d897747c8d2af92bcd to your computer and use it in GitHub Desktop.
package main
import (
"encoding/binary"
"errors"
"fmt"
"io"
"net"
"os"
"syscall"
)
func main() {
fmt.Println("Hello, World")
}
func SendFile(file os.File, conn net.Conn) error {
fileInfo, err := file.Stat()
if err != nil {
return err
}
sizeBuf := make([]byte, 8)
binary.LittleEndian.PutUint64(sizeBuf, uint64(fileInfo.Size()))
_, err = conn.Write(sizeBuf)
if err != nil {
return err
}
buf := make([]byte, 1024)
for {
n, err := file.Read(buf)
if err == io.EOF {
break
}
if err != nil {
return err
}
_, err = conn.Write(buf[:n])
if err != nil {
return err
}
}
return nil
}
func SendFileTwo(file os.File, conn net.Conn) error {
fileInfo, err := file.Stat()
if err != nil {
return err
}
sizeBuf := make([]byte, 8)
binary.LittleEndian.PutUint64(sizeBuf, uint64(fileInfo.Size()))
_, err = conn.Write(sizeBuf)
if err != nil {
return err
}
tcpConn, ok := conn.(*net.TCPConn)
if !ok {
return errors.New("Casting error")
}
tcpFile, err := tcpConn.File()
if err != nil {
return err
}
_, err = syscall.Sendfile(int(tcpFile.Fd()), int(file.Fd()), nil, int(fileInfo.Size()))
if err != nil {
return err
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment