aboutsummaryrefslogtreecommitdiff
path: root/main.go
blob: 38ccd345a86bb6da7593e3cad7886b78f53ef1a3 (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
68
69
70
71
72
73
74
75
76
77
78
79
80
package main

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


var db RedisDB

func main() {
	db = RedisDB{data: make(map[string]any)}

	listener, err := net.Listen("tcp", ":6379")
	if err != nil {
		fmt.Println("error starting server: ", err)
		os.Exit(1)
	}
	defer listener.Close()
	fmt.Println("Redis clone listening on port 6379...")

	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println("Error accepting connection:", err)
			continue
		}
		go handleConnection(conn)
	}
}

func handleConnection(conn net.Conn) {
	defer conn.Close()
	fmt.Println("Client connected:", conn.RemoteAddr())

	reader := bufio.NewReader(conn)
	for {
		args, err := parseRESP(reader)
		if err != nil {
			fmt.Println("Client disconnected or error parsing:", conn.RemoteAddr(), err)
			return
		}

		if len(args) == 0 {
			continue
		}

		fmt.Printf("Parsed RESP Arguments: %v\n", args)

		command := strings.ToUpper(args[0])

		switch {
		case command == "GET" && len(args) == 2:
			handleGet(conn, args)
		case command == "SET" && len(args) == 3:
			handleSet(conn, args)
		case command == "EXISTS" && len(args) == 2:
			handleExists(conn, args)
		case command == "DEL" && len(args) == 2:
			handleDel(conn, args)
		case command == "INCR" && len(args) == 2:
			handleIncr(conn, args)
		case command == "DECR" && len(args) == 2:
			handleDecr(conn, args)
		case command == "PING" && len(args) == 1:
			handlePing(conn, args)
		case command == "FLUSHALL" && len(args) == 1:
			handleFlushall(conn, args)
		case command == "RPUSH" && len(args) >= 3:
            handleRpush(conn, args)
		case command == "LRANGE" && len(args) == 4:
            handleLrange(conn, args)
		default:
			conn.Write([]byte("-ERR unknown command or wrong arguments\r\n"))
		}
	}
}