package main

import (

"fmt"
"github.com/getlantern/systray"
"github.com/getlantern/systray/example/icon"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"

)

var server *http.Server

func main() {

startServer()
systray.Run(onReady, onExit)

}

func onReady() {

systray.SetTitle("My Tool")
systray.SetTooltip("My handy tool")
systray.SetIcon(icon.Data)
startItem := systray.AddMenuItem("开始", "启动 HTTP 服务")
endItem := systray.AddMenuItem("结束", "停止 HTTP 服务")
quitItem := systray.AddMenuItem("退出", "退出软件")

go func() {
    for {
        select {
        case <-startItem.ClickedCh:
            startServer()
        case <-endItem.ClickedCh:
            stopServer()
        case <-quitItem.ClickedCh:
            systray.Quit()
        }
    }
}()

}

func startServer() {

// 获取当前目录下的 www 目录作为 web 目录
currentDir, err := os.Getwd()
if err != nil {
    log.Fatal(err)
}
webDir := filepath.Join(currentDir, "www")

mux := http.NewServeMux()

// 注册静态文件服务器
mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(webDir))))

// 注册路由处理器
mux.HandleFunc("/sendParams", sendParamsHandler)

// 创建服务器
server = &http.Server{
    Addr:    ":8080",
    Handler: mux,
}

fmt.Println("Starting server...")
go func() {
    err := server.ListenAndServe()
    if err != nil && err != http.ErrServerClosed {
        log.Fatal(err)
    }
}()

openBrowser("http://localhost:8080")

}
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)

} else {
    http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
}

}
func stopServer() {

fmt.Println("Stopping server...")
if server != nil {
    err := server.Close()
    if err != nil {
        log.Fatal(err)
    }
}

}

func onExit() {

// 这里可以添加退出时的清理逻辑
if server != nil {
    stopServer()
}

}

func openBrowser(url string) {

var err error
switch runtime.GOOS {
case "linux":
    err = exec.Command("xdg-open", url).Start()
case "windows":
    err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
case "darwin":
    err = exec.Command("open", url).Start()
default:
    fmt.Println("Unsupported platform")
}
if err != nil {
    log.Fatal(err)
}

}

前端

<!DOCTYPE html>
<html lang="en">
<head>

<meta charset="UTF-8">
<title>使用GO语言开发Web服务</title>

</head>
<body>
<button id="sendButton">发送单个参数</button>
<button id="sendButton2">发送多个参数</button>
<button id="sendButton3">请求json数据</button>
<button id="closeSys">关闭服务</button>

表格

<script>

document.getElementById('sendButton').addEventListener('click', function() {
    const param = 'Hello, World!';
    console.log('发送请求');

    fetch('/sendParams', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: `param=${encodeURIComponent(param)}`
    })
        .then(response => response.text())
        .then(data => console.log(data))
        .catch(error => console.error('Error:', error));
});
document.getElementById('sendButton2').addEventListener('click', function() {
    const param = { message: 'Hello, World!',aaa:'aaa' };
    console.log('发送请求');

    fetch('http://localhost:8080/sendMoreParams', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(param)
    })
        .then(response => response.text())
        .then(data => console.log('Response:', data))
        .catch(error => console.error('Error:', error));
});
document.getElementById('sendButton3').addEventListener('click', function() {
    const param = { message: 'Hello, World!',aaa:'aaa' };
    console.log('发送请求');

    fetch('http://localhost:8080/getJsonData', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(param)
    })
        .then(response => response.text())
        .then(data => console.log('Response:', data))
        .catch(error => console.error('Error:', error));
});
document.getElementById('closeSys').addEventListener('click', function() {
    const param = { message: 'Hello, World!',aaa:'aaa' };
    console.log('发送请求');

    fetch('http://localhost:8080/closeSys', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(param)
    })
        .then(response => response.text())
        .then(data => console.log('Response:', data))
        .catch(error => console.error('Error:', error));
});

</script>
</body>
</html>

标签: none

相关阅读

  • 测试信息
  • 开发商:阿里巴巴
  • 版本号:1.0
  • 配色:(企业家)” 推选活动结果
  • 测试信息
  • 测试信息
  • 测试信息