aboutsummaryrefslogtreecommitdiff
path: root/app/server.go
blob: b4dd7eeb1b6476a8506475f21720db6f85adf3ad (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
58
59
60
61
62
63
64
65
66
67
package main

import (
	"fmt"
	"net"
	"os"
	"strings"
)

func main() {
	l, err := net.Listen("tcp", "0.0.0.0:4221")
	if err != nil {
		fmt.Println("Failed to bind to port 4221")
		os.Exit(1)
	}

	conn, err := l.Accept()
	if err != nil {
		fmt.Println("Error accepting connection: ", err.Error())
		os.Exit(1)
	}

	request, err := NewRequest(conn)
	if err != nil {
		fmt.Println("Error getting target: ", err.Error())
		os.Exit(1)
	}

	if request.Target == "/" {
		_, err = conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\n"))
		if err != nil {
			fmt.Println("Error connection write: ", err.Error())
		}
	} else if strings.HasPrefix(request.Target, "/echo/") {
		message := strings.SplitN(request.Target, "/", 3)[2]

		_, err = conn.Write([]byte("HTTP/1.1 200 OK\r\n"))
		if err != nil {
			fmt.Println("Error connection write: ", err.Error())
		}

		_, err = conn.Write([]byte("Content-Type: text/plain\r\n"))
		if err != nil {
			fmt.Println("Error connection write: ", err.Error())
		}

		_, err = conn.Write([]byte(fmt.Sprintf("Content-Length: %d\r\n", len(message))))
		if err != nil {
			fmt.Println("Error connection write: ", err.Error())
		}

		_, err = conn.Write([]byte("\r\n"))
		if err != nil {
			fmt.Println("Error connection write: ", err.Error())
		}

		_, err = conn.Write([]byte(message))
		if err != nil {
			fmt.Println("Error connection write: ", err.Error())
		}
	} else {
		_, err = conn.Write([]byte("HTTP/1.1 404 Not Found\r\n\r\n"))
		if err != nil {
			fmt.Println("Error connection write: ", err.Error())
		}
	}
}