file.go 1.77 KB
Newer Older
Lei Li's avatar
Lei Li committed
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
package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path"
	"path/filepath"
	"time"

	"linkfog.com/public/lib/l"
)

func DownloadFile(file, url string) error {
	// URL of the file to be downloaded
	defer l.Info("exited download file")
	versionFile := path.Join(RootDir, file)

	// Send HTTP GET request
	response, err := HttpGet(url, nil)
	if err != nil {
		l.Error("get method failed:", err)
		return err
	}
	defer response.Body.Close()

	if response.StatusCode != http.StatusOK {
		return fmt.Errorf("url:%s, response status code: %d", url, response.StatusCode)
	}

	// Create the file
	out, err := os.Create(versionFile)
	if err != nil {
		l.Error("create new file failed:", err)
		return err
	}
	defer out.Close()

	// Write the body to file
	_, err = io.Copy(out, response.Body)
	if err != nil {
		l.Error("copy new file failed:", err)
		return err
	}
	l.Info("download new file success!!!")
	return nil
}

func HttpGet(url string, body []byte) (*http.Response, error) {
	client := http.Client{}
	req, _ := http.NewRequest("GET", url, bytes.NewBuffer(body))
	//req.Header.Set("Content-Type", "application/json")
	return client.Do(req)
}

func startAgent() {
Lei Li's avatar
Lei Li committed
60
	msg := ""
Lei Li's avatar
Lei Li committed
61
62
63
64
65
66
	for {
		agent := exec.Command(filepath.Join(RootDir, agentFileName), "-vendor=test")
		// 启动子进程
		err := agent.Start()
		if err != nil {
			l.Errorf("agent start failed: %v", err)
Lei Li's avatar
Lei Li committed
67
68
			msg = fmt.Sprintf("agent start failed: %s", err.Error())
			LogError("MainActivity", msg)
Lei Li's avatar
Lei Li committed
69
70
71
72
73
74
75
76
77
			time.Sleep(10 * time.Second)
			continue
		}

		childPID = agent.Process.Pid
		// 等待子进程结束
		err = agent.Wait()
		if err != nil {
			l.Errorf("agent wait failed: %v", err)
Lei Li's avatar
Lei Li committed
78
79
80
			msg = fmt.Sprintf("agent wait failed: %s", err.Error())
			LogError("MainActivity", msg)
			break
Lei Li's avatar
Lei Li committed
81
		}
Lei Li's avatar
Lei Li committed
82
		//time.Sleep(10 * time.Second)
Lei Li's avatar
Lei Li committed
83
84
	}
}