golang 网络编程

目录

  • 1. golang 网络编程
    • 1.1. Listening to Random Available Port

1. golang 网络编程

1.1. Listening to Random Available Port

package main
import (
    "log"
    "net"
    "net/http"
)
func createListener() (l net.Listener, close func()) {
    l, err := net.Listen("tcp", ":0")
    if err != nil {
        panic(err)
    }
return l, func() {
        _ = l.Close()
    }
}
func main() {
    l, close := createListener()
    defer close()
http.Handle("/", http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
        // handle like normal
    }))
log.Println("listening at", l.Addr().(*net.TCPAddr).Port)
    http.Serve(l, nil)
}
func GetFreePort() uint16 {
	var port uint16
	for i := 0; i < 5; i++ {
		conn, err := net.ListenPacket("udp", ":0")
		if err != nil {
			continue
		}
		conn.Close()
		port, err = parsePort(conn.LocalAddr().String())
		if err != nil {
			continue
		}
		return port
	}
	panic("unable to find free port for starting the trap listener")
}

func parsePort(addr string) (uint16, error) {
	_, portString, err := net.SplitHostPort(addr)
	if err != nil {
		return 0, err
	}

	port, err := strconv.ParseUint(portString, 10, 16)
	if err != nil {
		return 0, err
	}
	return uint16(port), nil
}

你可能感兴趣的:(#,golang_code,golang,network,listen,http,tcp)