-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
58 lines (51 loc) · 1.21 KB
/
main.go
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
51
52
53
54
55
56
57
58
package main
import (
"flag"
"fmt"
"net"
"os"
"os/signal"
"syscall"
)
var (
ConnPort = flag.Int("port", 4568, "Sets the port to listen on.")
ConnHost = flag.String("host", "localhost", "Sets the host to listen on.")
)
func main() {
go runListener()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
fmt.Println("Press ctrl+c to shutdown")
<- c
fmt.Println("ctrl+c detected. Shutting down")
}
func runListener() {
flag.Parse()
// Listen for incoming connections.
host, port := *ConnHost, *ConnPort
address := fmt.Sprintf("%s:%d", host, port)
l, err := net.Listen("tcp", address)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
// Close the listener when the application closes.
defer l.Close()
fmt.Println("Listening on " + address)
for {
// Listen for an incoming connection.
conn, err := l.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
os.Exit(1)
}
// Handle connections in a new goroutine.
go handleRequest(conn)
}
}
// Handles incoming requests.
func handleRequest(conn net.Conn) {
fmt.Printf("Got connection %s\n", conn.RemoteAddr().String())
// Close the connection immediately
conn.Close()
}