-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathmain.go
More file actions
50 lines (42 loc) · 840 Bytes
/
Copy pathmain.go
File metadata and controls
50 lines (42 loc) · 840 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package main
// A simple echo server. It listens on a random port, prints that port, then
// echos back anything sent to it.
import (
"errors"
"fmt"
"io"
"log"
"net"
)
func main() {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
log.Fatalf("listen error: err=%s", err)
}
defer l.Close()
tcpAddr, valid := l.Addr().(*net.TCPAddr)
if !valid {
log.Panic("address is not valid")
}
remotePort := tcpAddr.Port
_, err = fmt.Println(remotePort)
if err != nil {
log.Panicf("print error: err=%s", err)
}
for {
conn, err := l.Accept()
if err != nil {
log.Panicf("accept error, err=%s", err)
return
}
go func() {
defer conn.Close()
_, err := io.Copy(conn, conn)
if errors.Is(err, io.EOF) {
return
} else if err != nil {
log.Panicf("copy error, err=%s", err)
}
}()
}
}