-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
72 lines (61 loc) · 1.51 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"fmt"
"io"
"log"
"net/http"
"os"
"sync"
"syscall"
)
var port = "9924"
var fifoPath = "./fifo"
const bufSize = 8 * 1024 * 1024
func main() {
if f, exists := os.LookupEnv("FIFO_PATH"); exists {
fifoPath = f
}
if p, exists := os.LookupEnv("PORT"); exists {
port = p
}
http.HandleFunc("/", ReceiveHandler)
http.HandleFunc("/receive", ReceiveHandler)
http.HandleFunc("/transmit", TransmitHandler)
if err := syscall.Mkfifo(fifoPath, 0o750); err != nil {
panic(err)
}
log.Fatal(http.ListenAndServe(":"+port, nil))
}
var mut sync.Mutex
func ReceiveHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Waiting for lock...")
mut.Lock()
defer mut.Unlock()
fmt.Println("New request (receive):", r.RemoteAddr)
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("Content-Disposition", "attachment")
fifo, err := os.OpenFile("./fifo", os.O_RDONLY, os.ModeNamedPipe)
if err != nil {
panic(err)
}
w.WriteHeader(200)
if _, err := io.CopyBuffer(w, fifo, make([]byte, bufSize)); err != nil {
fmt.Println(err)
}
_ = fifo.Close()
}
func TransmitHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Waiting for lock...")
mut.Lock()
defer mut.Unlock()
fmt.Println("New request (transmit):", r.RemoteAddr)
fifo, err := os.OpenFile("./fifo", os.O_WRONLY, os.ModeNamedPipe)
if err != nil {
panic(err)
}
w.WriteHeader(200)
if _, err := io.CopyBuffer(fifo, r.Body, make([]byte, bufSize)); err != nil {
fmt.Println(err)
}
_ = fifo.Close()
}