Skip to content

Commit

Permalink
优化安装
Browse files Browse the repository at this point in the history
  • Loading branch information
Jrohy committed Mar 28, 2020
1 parent e2e0fb9 commit ba01a20
Showing 1 changed file with 26 additions and 29 deletions.
55 changes: 26 additions & 29 deletions util/command.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
package util

import (
"bufio"
"fmt"
"io"
"io/ioutil"
"net/http"
"os/exec"
Expand Down Expand Up @@ -35,25 +35,6 @@ func RunWebShell(webShellPath string) {
ExecCommand(string(installShell))
}

func asyncLog(reader io.ReadCloser) error {
cache := "" //缓存不足一行的日志信息
buf := make([]byte, 1024)
for {
num, err := reader.Read(buf)
if err != nil && err != io.EOF {
return err
}
if num > 0 {
b := buf[:num]
s := strings.Split(string(b), "\n")
line := strings.Join(s[:len(s)-1], "\n") //取出整行的日志
fmt.Printf("%s%s\n", cache, line)
cache = s[len(s)-1]
}
}
return nil
}

// ExecCommand 运行命令并实时查看运行结果
func ExecCommand(command string) error {
cmd := exec.Command("bash", "-c", command)
Expand All @@ -65,17 +46,33 @@ func ExecCommand(command string) error {
fmt.Println("Error:The command is err: ", err.Error())
return err
}

go asyncLog(stdout)
go asyncLog(stderr)

if err := cmd.Wait(); err != nil {
if !strings.Contains(err.Error(), "exit status") {
fmt.Println("wait:", err.Error())
ch := make(chan string, 100)
stdoutScan := bufio.NewScanner(stdout)
stderrScan := bufio.NewScanner(stderr)
go func() {
for stdoutScan.Scan() {
line := stdoutScan.Text()
ch <- line
}
return err
}()
go func() {
for stderrScan.Scan() {
line := stderrScan.Text()
ch <- line
}
}()
var err error
go func() {
err = cmd.Wait()
if err != nil {
fmt.Println("Error:The command is err: ", err.Error())
}
close(ch)
}()
for line := range ch {
fmt.Println(line)
}
return nil
return err
}

// ExecCommandWithResult 运行命令并获取结果
Expand Down

0 comments on commit ba01a20

Please sign in to comment.