Skip to content

Instantly share code, notes, and snippets.

@up1
Last active December 15, 2024 05:10
Show Gist options
  • Save up1/76cf141dc51e69ed7d87de949d8f2826 to your computer and use it in GitHub Desktop.
Save up1/76cf141dc51e69ed7d87de949d8f2826 to your computer and use it in GitHub Desktop.
RESP protocol with Go
# ฝั่ง Redis-cli
127.0.0.1:6379> set counter 1
OK
# ฝั่ง Server
Received: *3\r\n$3\r\nset\r\n$7\r\ncounter\r\n$1\r\n1\r\n
แสดงผลใน terminal
set
$7
counter
$1
1
$go run main.go
TCP Server starting at 0.0.0.0:6379
Connection accepted from 127.0.0.1:63897
Received: *2
$7
COMMAND
$4
DOCS
package main
import (
"fmt"
"net"
)
// Address and port to bind to
const addr = "0.0.0.0:6379"
func main() {
// Binding to TCP port 6379
listen, err := net.Listen("tcp", addr)
if err != nil {
panic(err)
}
fmt.Println("TCP Server starting at ", addr)
for {
conn, err := listen.Accept()
if err != nil {
fmt.Println("Error accepting connection: ", err)
break
}
defer conn.Close()
fmt.Println("Connection accepted from ", conn.RemoteAddr())
go handleRequest(conn)
}
}
func handleRequest(conn net.Conn) {
buf := make([]byte, 1024)
for {
// Read the incoming connection into the buffer
n, err := conn.Read(buf)
if err != nil {
fmt.Println("Error reading: ", err)
break
}
if n == 0 {
break
}
// Print the received data
fmt.Println("Received: ", string(buf[:n]))
conn.Write([]byte("+OK\r\n"))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment