blob: 0e96d2cfeab35506cedb99136860b784e14c1780 [file] [log] [blame]
giolekvaea7ac412021-08-01 14:18:26 +04001// Copyright 2018 Venil Noronha. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package main
6
7import (
8 "bufio"
9 "flag"
10 "fmt"
11 "io"
12 "net"
13 "os"
14)
15
16var port = flag.Int("port", 3000, "Port to listen on")
17
18// main serves as the program entry point
19func main() {
20 flag.Parse()
21 // create a tcp listener on the given port
22 listener, err := net.Listen("tcp", fmt.Sprintf(":%d", *port))
23 if err != nil {
24 fmt.Println("failed to create listener, err:", err)
25 os.Exit(1)
26 }
27 fmt.Printf("listening on %s\n", listener.Addr())
28
29 // listen for new connections
30 for {
31 conn, err := listener.Accept()
32 if err != nil {
33 fmt.Println("failed to accept connection, err:", err)
34 continue
35 }
36
37 // pass an accepted connection to a handler goroutine
38 go handleConnection(conn)
39 }
40}
41
42// handleConnection handles the lifetime of a connection
43func handleConnection(conn net.Conn) {
44 defer conn.Close()
45 reader := bufio.NewReader(conn)
46 for {
47 // read client request data
48 bytes, err := reader.ReadBytes(byte('\n'))
49 if err != nil {
50 if err != io.EOF {
51 fmt.Println("failed to read data, err:", err)
52 }
53 return
54 }
55 fmt.Printf("request: %s", bytes)
56 conn.Write(bytes)
57 }
58}