package main

import (
	"fmt"
	"net/http"
	"os"
	"os/exec"
)

// 处理请求的Handler函数
func pingHandler(w http.ResponseWriter, r *http.Request) {
	// 获取IP地址参数
	ip := r.FormValue("ip")

	if ip == "" {
		http.Error(w, "Missing IP address", http.StatusBadRequest)
		return
	}
	fmt.Println(ip)
	// 执行ping命令
	cmd := exec.Command("sh", "-c", "ping -c 2 " + ip)

	// 捕获命令执行结果
	output, err := cmd.CombinedOutput()
	if err != nil {
		http.Error(w, fmt.Sprintf("Command execution error: %s", err.Error()), http.StatusInternalServerError)
		return
	}

	// 将命令执行结果返回给客户端
	w.Header().Set("Content-Type", "text/plain")
	w.Write(output)
}

func main() {
	// 注册处理请求的Handler函数
	http.HandleFunc("/ping", pingHandler)

	// 启动WEB服务
	err := http.ListenAndServe(":8084", nil)
	if err != nil {
		fmt.Printf("Failed to start server: %s\n", err.Error())
		os.Exit(1)
	}
}
