/
redirector_other.go
58 lines (45 loc) · 1.01 KB
/
redirector_other.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
//go:build !windows
package proc
import (
"crypto/rand"
"encoding/hex"
"io"
"os"
"path/filepath"
"syscall"
)
type openOnRead struct {
path string
rd io.ReadCloser
}
func (oor *openOnRead) Read(p []byte) (n int, err error) {
if oor.rd != nil {
return oor.rd.Read(p)
}
fh, err := os.OpenFile(oor.path, os.O_RDONLY, os.ModeNamedPipe)
if err != nil {
return 0, err
}
oor.rd = fh
return oor.rd.Read(p)
}
func (oor *openOnRead) Close() error {
defer os.Remove(oor.path)
fh, _ := os.OpenFile(oor.path, os.O_WRONLY|syscall.O_NONBLOCK, 0)
if fh != nil {
fh.Close()
}
return oor.rd.Close()
}
func Redirector() (reader io.ReadCloser, output OutputRedirect, err error) {
r := make([]byte, 4)
if _, err = rand.Read(r); err != nil {
return reader, output, err
}
var path = filepath.Join(os.TempDir(), hex.EncodeToString(r))
if err = syscall.Mkfifo(path, 0o600); err != nil {
_ = os.Remove(path)
return reader, output, err
}
return &openOnRead{path: path}, OutputRedirect{Path: path}, nil
}