首页 > 解决方案 > 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 程序的信息。简而言之,不是运行,而是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 程序。


推荐阅读