Proof of concept for delivering files over gob structs

This commit is contained in:
raul 2024-06-14 09:03:39 +02:00
parent e9d72b09fe
commit 9b33642a4e
5 changed files with 92 additions and 0 deletions

3
gob-file/client/go.mod Normal file
View File

@ -0,0 +1,3 @@
module client
go 1.22.4

BIN
gob-file/client/gopher.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 160 KiB

44
gob-file/client/main.go Normal file
View File

@ -0,0 +1,44 @@
package main
import (
"encoding/gob"
"io"
"log"
"net"
"os"
)
type File struct {
Filename string
File []byte
}
func main() {
conn, err := net.Dial("tcp", "127.0.0.1:1337")
if err != nil {
log.Fatal(err)
}
defer conn.Close()
f, err := os.Open("./gopher.png")
if err != nil {
log.Fatal(err)
}
defer f.Close()
contents, err := io.ReadAll(f)
if err != nil {
log.Fatal(err)
}
fileToSend := File{
Filename: f.Name(),
File: contents,
}
enc := gob.NewEncoder(conn)
err = enc.Encode(&fileToSend)
if err != nil {
log.Fatal(err)
}
}

3
gob-file/go.mod Normal file
View File

@ -0,0 +1,3 @@
module gob-file
go 1.22.4

42
gob-file/main.go Normal file
View File

@ -0,0 +1,42 @@
package main
import (
"encoding/gob"
"fmt"
"log"
"net"
"os"
)
type File struct {
Filename string
File []byte
}
func main() {
fmt.Println("Listening on port 1337")
ln, err := net.Listen("tcp", ":1337")
if err != nil {
log.Fatal(err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
}
go receiveFile(conn)
}
}
func receiveFile(conn net.Conn) {
dec := gob.NewDecoder(conn)
c := File{}
err := dec.Decode(&c)
if err != nil {
log.Println(err)
return
}
err = os.WriteFile("./foobar.png", c.File, 0664)
}