| giolekva | ea7ac41 | 2021-08-01 14:18:26 +0400 | [diff] [blame^] | 1 | // 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 | |
| 5 | package main |
| 6 | |
| 7 | import ( |
| 8 | "bufio" |
| 9 | "flag" |
| 10 | "fmt" |
| 11 | "io" |
| 12 | "net" |
| 13 | "os" |
| 14 | ) |
| 15 | |
| 16 | var port = flag.Int("port", 3000, "Port to listen on") |
| 17 | |
| 18 | // main serves as the program entry point |
| 19 | func 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 |
| 43 | func 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 | } |