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?
Information on how to cross-compile a Go program for different operation systems can be found here. Briefly, instead of running go build main.go
, run:
env GOARCH=amd64 GOOS=<target_OS> CGO_ENABLED=1 go build -v main.go
I usually have a Makefile to simplify the process of cross-compiling for linux, windows, and macOS.
With regard to your second question, I can only reproduce your error on my machine when I try to ListenAndServe
twice. I.e. I suspect that during your debugging cycles, you forgot to close a running server while trying to start a new instance in another terminal window. Make sure to abort your Go program with ctrl + c
before running it again.