RandomPort() returns a random port to be used with net.Listen(). It's an helper function to register to kontrol before binding to a port. Note that this racy, there is a possibility that someoe binds to the port during the time you get the port and someone else finds it. Therefore use in caution.
()
| 50 | // this racy, there is a possibility that someoe binds to the port during the |
| 51 | // time you get the port and someone else finds it. Therefore use in caution. |
| 52 | func RandomPort() (int, error) { |
| 53 | l, err := net.Listen("tcp", ":0") |
| 54 | if err != nil { |
| 55 | return 0, err |
| 56 | } |
| 57 | defer l.Close() |
| 58 | |
| 59 | _, port, err := net.SplitHostPort(l.Addr().String()) |
| 60 | if err != nil { |
| 61 | return 0, err |
| 62 | } |
| 63 | |
| 64 | return strconv.Atoi(port) |
| 65 | } |