-
Notifications
You must be signed in to change notification settings - Fork 1
/
setup_server.go
115 lines (103 loc) · 2.46 KB
/
setup_server.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"archive/tar"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
)
const requiredVersion = "1.14.8"
func setupServer() error {
file, err := os.Open("httptoolkit-server/package.json")
if err != nil {
return downloadServer()
}
defer file.Close()
var pkg struct{ Version string }
if err = json.NewDecoder(file).Decode(&pkg); err != nil {
return downloadServer()
}
if pkg.Version != requiredVersion {
return downloadServer()
}
return nil
}
func downloadServer() error {
fmt.Println("Downloading httptoolkit-server " + requiredVersion + " for " + platform)
fileName := "httptoolkit-server.tar.gz"
err := dl(
fmt.Sprintf(
"https://github.com/juby-httptoolkit/httptoolkit-server/releases/download/v%s/httptoolkit-server-v%s-%s-x64.tar.gz",
requiredVersion, requiredVersion, platform,
),
fileName,
)
if err != nil {
return err
}
file, err := os.Open(fileName)
if err != nil {
return err
}
err = extract(file)
file.Close()
if err != nil {
return err
}
os.Remove(fileName)
fmt.Println("Server download completed")
return nil
}
func dl(url, path string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
file, err := os.Create(path)
if err != nil {
return err
}
_, err = io.Copy(file, resp.Body)
if err != nil {
return err
}
return file.Close()
}
// https://codereview.stackexchange.com/questions/272457/decompress-tar-gz-file-in-go
func extract(gzipStream io.Reader) error {
uncompressedStream, err := gzip.NewReader(gzipStream)
if err != nil {
return err
}
tarReader := tar.NewReader(uncompressedStream)
var header *tar.Header
for header, err = tarReader.Next(); err == nil; header, err = tarReader.Next() {
switch header.Typeflag {
case tar.TypeDir:
if _, err := os.Stat(header.Name); err != nil {
if err := os.Mkdir(header.Name, 0755); err != nil {
return fmt.Errorf("extract: Mkdir() failed: %w", err)
}
}
case tar.TypeReg:
outFile, err := os.OpenFile(header.Name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777)
if err != nil {
return fmt.Errorf("extract: Create() failed: %w", err)
}
if _, err = io.Copy(outFile, tarReader); err != nil {
outFile.Close()
return fmt.Errorf("extract: Copy() failed: %w", err)
}
if err = outFile.Close(); err != nil {
return fmt.Errorf("extract: Close() failed: %w", err)
}
}
}
if err != io.EOF {
return fmt.Errorf("extract: Next() failed: %w", err)
}
return nil
}