Created
February 3, 2023 18:27
-
-
Save dharanad/d54ddad2fc6ff1d897747c8d2af92bcd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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