Skip to content

Instantly share code, notes, and snippets.

@fxsjy
Created Aug 17, 2012
Embed
What would you like to do?
Memcached Server Written in Go, only 70 lines of code
package main
import (
"net"
"log"
"fmt"
"bufio"
"strings"
"strconv"
"io"
"runtime"
)
type Item struct {
value []byte
flag int
expire int
}
var store = make(map[string]*Item)
func handleConnection(conn net.Conn){
log.Println(conn.RemoteAddr())
var reader = bufio.NewReader(conn)
var writer = bufio.NewWriter(conn)
var header = ""
var err error
for {
header,err = reader.ReadString('\n')
if err!=nil{
return
}
var tup = strings.Fields(header)
var cmd = tup[0]
switch cmd {
case "get":
key:=tup[1]
obj, ok := store[key]
if ok {
fmt.Fprintf(writer, "VALUE %s %d %d\r\n",key,obj.flag,len(obj.value))
writer.Write(obj.value)
io.WriteString(writer,"\r\n")
}
io.WriteString(writer,"END\r\n")
case "set":
key := tup[1]
value_len,_ := strconv.Atoi(tup[4])
value := make([]byte,value_len)
io.ReadFull(reader,value)
obj := &Item{value:value}
flag, _ := strconv.Atoi(tup[2])
expire,_ := strconv.Atoi(tup[2])
obj.flag = flag
obj.expire = expire
store[key] = obj
reader.ReadString('\n')//skip CRLR
io.WriteString(writer,"STORED\r\n")
case "delete":
delete(store,tup[1])
io.WriteString(writer,"DELETED\r\n")
default:
io.WriteString(writer,"ERROR\r\n")
}
writer.Flush()
}
}
func main(){
runtime.GOMAXPROCS(4)
ln, err := net.Listen("tcp", ":11211")
if err != nil {
// handle error
}
for {
conn, err := ln.Accept()
if err != nil {
// handle error
continue
}
go handleConnection(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment