检测端口占用
func CheckPort(port int) error {
checkStatement := fmt.Sprintf(`netstat -anp | grep -q %d ; echo $?`, port)
output, err := exec.Command("sh", "-c", checkStatement).CombinedOutput()
if err != nil {
return err
}
// log.Println(output, string(output)) ==> [48 10] 0 或 [49 10] 1
result, err := strconv.Atoi(strings.TrimSuffix(string(output), "\n"))
if err != nil {
return err
}
if result == 0 {
return fmt.Errorf("端口%d已被占用", port)
}
return nil
}
result, err := strconv.Atoi(string(output))strconv.Atoi: parsing "0\n": invalid syntaxCombinedOutput()0\n(1\n)\nstrings.TrimSuffix()\nstrings.TrimSuffix()strings.TrimRight()TrimRight(s string, cutset string) stringscutsetstrings.TrimRight("abcdabcdaaaaeac", "abcd")"abcdabcdaaaae"strings.TrimRight("abcdaaaaa", "abcd")""TrimSuffix(s, suffix string) stringsuffix