about summary refs log tree commit diff
path: root/example-service/main.go
blob: f32c2736ddfc659c4d042442e819af21dc3422e4 (plain)
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
package main

import (
    "net"
    "log"
    "os"
    "fmt"
)

const(
    CONN_HOST = "127.0.0.1"
    CONN_PORT = "3333"
    CONN_TYPE = "tcp"
)

func main() {
    // start a new listener
    l, err := net.Listen(CONN_TYPE, CONN_HOST + ":" + CONN_PORT)
    if err != nil {
        log.Printf("Error listening: %v", err)
        os.Exit(1)
    }

    // close the listener when done
    defer l.Close()

    for {
        // accept a connection
        conn, err := l.Accept()

        if err != nil {
            log.Printf("Error accepting: %v", err)
            os.Exit(1)
        }

        // handle the connection in a new go thread
        handlerequest(conn)
    }
}

func handlerequest(conn net.Conn) {
    // creat a buffer storing the incomming data
    buf := make([]byte, 10000)

    // read from the connection into the buffer
    reqLen, err := conn.Read(buf)
    if err != nil {
        log.Printf("Error reading: %v", err)
        os.Exit(1)
    }

    fmt.Println(string(buf))

    // write back how many bytes were sent
    conn.Write([]byte(fmt.Sprintf("Read %d bytes", reqLen)))
    conn.Close()
}