One page REST api go server to return system MAC address

I have a PHP based web application. On login page it do ajax call to Go server (located on client machine) to get MAC address. Below is 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.

  1. sometimes i got error “panic: listen tcp :8000: bind: address already in use” and i manually kill the process. So what can be improvement in code to avoid error and close previously running server

  2. Can alone go compiled file (created on ubuntu) be run on other systems windows or linux or mac without having go libs and setup

First time on this forum, so if any improvement in way of asking question then please suggest.

Your first issue sounds odd and the best I could come up with it was this thread: "bind: address already in use" even after listener closed
Where it gets mentioned that this behavior sometimes occurs when defining the serving address as just the port id.

As for your second question, you must build your binary executable for whatever Operating System and Architecture you intend to deploy to: https://www.digitalocean.com/community/tutorials/how-to-build-go-executables-for-multiple-platforms-on-ubuntu-16-04

1 Like

Thanks for quick response.
I created executable files as per link shared by you. One of them is for linux amd64. Its getting run on my machine but not on other linux amd64 machine. I am able to find ‘Run’ option when right click on compiled file but on other system ‘Run’ option not there. Did i miss anything ? Kindly help.

You’ll probably need to execute a chmod command to give the file executable permission: http://endlessgeek.com/2014/02/chmod-explained-linux-file-permissions/

basically open a terminal:

sudo chmod +x <filename>

should do the trick for you

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.