go - Go服务器上的一页REST api返回系统MAC地址
问题描述
我有一个基于 PHP 的 Web 应用程序。在登录页面上,它对 Go 服务器(位于客户端计算机上)进行 AJAX 调用以获取其 MAC 地址。下面是 Go 服务器代码:
包主
import (
"net"
"net/http"
"encoding/json"
)
//define struct for mac address json
type MacAddress struct {
Id string
}
/**
* Get device mac address
*/
func GetMacAddress(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
mac := &MacAddress{Id: ""}
ifas, err := net.Interfaces()
if err != nil {
json.NewEncoder(w).Encode(mac)
return
}
for _, ifa := range ifas {
a := ifa.HardwareAddr.String()
if a != "" {
mac := &MacAddress{Id: a}
json.NewEncoder(w).Encode(mac)
break
}
}
return
}
/**
* Main function
*/
func main() {
http.HandleFunc("/", GetMacAddress)
if err := http.ListenAndServe(":8000", nil); err != nil {
panic(err)
}
}
结果:
{Id: "8c:16:45:5h:1e:0e"}
在这里,我有 2 个问题。
有时我得到错误
panic: listen tcp :8000: bind: address already in use
我手动终止该进程。那么,在我的代码中可以改进什么来避免这个错误并关闭之前运行的服务器呢?
一个独立的编译 Go 文件(在 ubuntu 上创建)可以在其他系统上运行,比如 windows 或 linux 或 mac,而无需所有 Go 库和设置?
解决方案
可以在此处找到有关如何为不同操作系统交叉编译 Go 程序的信息。简而言之,不是运行,而是go build main.go
运行:
env GOARCH=amd64 GOOS=<target_OS> CGO_ENABLED=1 go build -v main.go
我通常有一个 Makefile 来简化 linux、windows 和 macOS 的交叉编译过程。
ListenAndServe
关于你的第二个问题,当我尝试两次时,我只能在我的机器上重现你的错误。即我怀疑在您的调试周期中,您在尝试在另一个终端窗口中启动新实例时忘记关闭正在运行的服务器。ctrl + c
确保在再次运行之前中止您的 Go 程序。
推荐阅读
- python - 为 PyPi 打包 Python 应用程序时如何修复 ModuleNotFoundError
- node.js - Nodejs中的Path.join跨平台要求
- javascript - 简单的云功能复制文档时出错
- node.js - 从服务器到客户端的 Socket.io 消息递增
- installation - 从源代码 Cmake 为 Scientific Linux 7.8 构建
- c# - 等效于 C# 类型参数中的 F# _ 通配符
- python - pygame rect大小没有改变
- javascript - 在发出 AJAX HTTP GET 请求后,如何处理浏览器刷新按钮的这种破坏行为?
- list - 创建 scala 列表的子列表
- javascript - 由javascript可折叠事件侦听器呈现的按钮不起作用