I have a PHP based web application. On the login page, it makes an AJAX call to a Go server (located on the client machine) to get its MAC address. Below is the Go server code:
package main
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)
}
}
Result:
{Id: "8c:16:45:5h:1e:0e"}
Here I have 2 questions.
Sometimes i get the error
panic: listen tcp :8000: bind: address already in use
and I manually kill the process. So, what can be improved in my code to avoid this error and close the previously running server?
Can a stand-alone, compiled Go file (created on ubuntu) be run on other systems like windows or linux or mac without having all Go libs and setup?