Created
November 6, 2017 23:03
-
-
Save akramsaouri/4e6e6fff0b227f3fee8642c61d2110b5 to your computer and use it in GitHub Desktop.
Simplified redis clone.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"io" | |
"log" | |
"net" | |
"strings" | |
) | |
var data = make(map[string]string) | |
func handle(conn net.Conn) { | |
defer conn.Close() | |
scanner := bufio.NewScanner(conn) | |
for scanner.Scan() { | |
ln := scanner.Text() | |
fs := strings.Fields(ln) | |
// skip black lines | |
if len(fs) < 2 { | |
continue | |
} | |
switch fs[0] { | |
case "GET": | |
// GET <KEY> | |
key := fs[1] | |
value := data[key] | |
fmt.Fprintf(conn, "%s\n", value) | |
case "SET": | |
// SET <KEY> | |
if len(fs) != 3 { | |
io.WriteString(conn, "INVALID VALUE") | |
continue | |
} | |
key := fs[1] | |
value := fs[2] | |
data[key] = value | |
case "DEL": | |
key := fs[1] | |
delete(data, key) | |
default: | |
io.WriteString(conn, "INVALID COMMAND "+fs[0]+"\n") | |
} | |
fmt.Println(fs) | |
} | |
} | |
func main() { | |
li, err := net.Listen("tcp", ":9000") | |
if err != nil { | |
log.Fatalln(err) | |
} | |
defer li.Close() | |
for { | |
conn, err := li.Accept() | |
if err != nil { | |
log.Fatalln(err) | |
} | |
handle(conn) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment