package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os/exec"
"runtime"
"time"
)
func openBrowser(url string) {
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("open", url)
case "linux":
cmd = exec.Command("xdg-open", url)
case "windows":
cmd = exec.Command("cmd", "/c", "start", url)
default:
log.Println("Unsupported OS")
return
}
err := cmd.Start()
if err != nil {
log.Printf("Failed to open browser: %v", err)
}
}
func main() {
// 设置静态文件服务目录为当前目录下的www文件夹
fs := http.FileServer(http.Dir("./www"))
// 添加一个新的路由来处理发送参数的请求
http.HandleFunc("/sendParams", sendParamsHandler)
http.HandleFunc("/sendMoreParams", sendMoreParamsHandler)
//另一个请求 http.HandleFunc("/anotherRequest", anotherRequestHandler)
// 将请求转发到静态文件服务器
// 使用http.HandleFunc来处理根URL("/")的请求
// 使用FileServer来服务静态文件
http.Handle("/", http.StripPrefix("/", fs))
openBrowser("http://localhost:8080")
// 设置服务器监听的端口
log.Println("Starting server on :8080")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
// sendParamsHandler 处理参数传输请求。
// 它接受 POST 请求,并解析请求体中的 "param" 参数。
// 在接收参数后,它会打印参数值,向客户端响应参数值,
// 并依次关闭 HTTP 服务器和浏览器。
func sendParamsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
r.ParseForm()
param := r.Form.Get("param")
fmt.Println("Received parameter:", param)
fmt.Fprintf(w, "Parameter received: %s", param)
// 关闭 HTTP 服务器
shutdownServer()
// 关闭浏览器
closeBrowser()
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}
// 处理发送参数的请求
func sendMoreParamsHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, "Error reading request body", http.StatusBadRequest)
return
}
defer r.Body.Close()
var param map[string]string
err = json.Unmarshal(body, ¶m)
if err != nil {
http.Error(w, "Error parsing JSON", http.StatusBadRequest)
return
}
message, ok := param["message"]
if !ok {
http.Error(w, "Missing 'message' field in JSON", http.StatusBadRequest)
return
}
aaa, ok := param["aaa"]
if !ok {
http.Error(w, "Missing 'message' field in JSON", http.StatusBadRequest)
return
}
fmt.Println("Received parameter:", aaa)
fmt.Println("Received parameter:", message)
fmt.Fprintf(w, "Parameter received: %s", message)
// 关闭 HTTP 服务器
//shutdownServer()
// 关闭浏览器
//closeBrowser()
} else {
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}
}
// 关闭 HTTP 服务器
func shutdownServer() {
server := &http.Server{Addr: ":8080"}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Could not gracefully shutdown the server: %v\n", err)
} else {
log.Println("Server gracefully shut down")
}
}
// 关闭浏览器
func closeBrowser() {
var cmd *exec.Cmd
switch runtime.GOOS {
case "darwin":
cmd = exec.Command("osascript", "-e", "tell application \"Safari\" to quit")
case "linux":
cmd = exec.Command("xdotool", "key", "Ctrl+Q")
case "windows":
cmd = exec.Command("taskkill", "/F", "/IM", "chrome.exe")
default:
log.Println("Unsupported OS")
return
}
err := cmd.Run()
if err != nil {
log.Printf("Failed to close browser: %v", err)
} else {
log.Println("Browser closed")
}
}