/
main.go
63 lines (58 loc) · 1.25 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
package main
import (
"archive/zip"
"io"
"io/ioutil"
"log"
"os"
"os/exec"
"path/filepath"
)
func main() {
// Open itself for reading.
r, err := zip.OpenReader(os.Args[0])
if err != nil {
log.Fatal(err)
}
defer r.Close()
dir, err := ioutil.TempDir("", "russian-doll-")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir)
log.Print("using temp dir ", dir)
// Iterate through the files in the archive.
for _, f := range r.File {
// On OS X, this works:
//out, err := exec.Command(filepath.Join(os.Args[0], f.Name)).CombinedOutput()
//
// But the more general solution is to explicitly extract the
// embedded binary out of the main binary:
out, err := execEmbeddedBinary(dir, f)
if err != nil {
log.Fatal(err)
}
log.Print(string(out))
}
}
func execEmbeddedBinary(tmpDir string, f *zip.File) ([]byte, error) {
tmpName := filepath.Join(tmpDir, f.Name)
rc, err := f.Open()
if err != nil {
return nil, err
}
defer rc.Close()
tmpFile, err := os.OpenFile(tmpName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return nil, err
}
_, err = io.Copy(tmpFile, rc)
if err != nil {
return nil, err
}
err = tmpFile.Close()
if err != nil {
return nil, err
}
return exec.Command(tmpName).CombinedOutput()
}