Created
June 24, 2025 12:12
-
-
Save alirezaarzehgar/ad11735b89ca27e54fd6ca02e8e06f46 to your computer and use it in GitHub Desktop.
LevelDB+Golang Hello World
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" | |
| "log" | |
| "os" | |
| "strings" | |
| "github.com/syndtr/goleveldb/leveldb" | |
| ) | |
| func main() { | |
| db, err := leveldb.OpenFile("kv.db", nil) | |
| if err != nil { | |
| log.Fatalf("failed to open/create database: %w\n", err) | |
| } | |
| defer db.Close() | |
| s := bufio.NewScanner(os.Stdin) | |
| for { | |
| fmt.Print("> ") | |
| if !s.Scan() { | |
| break | |
| } | |
| tokens := strings.Split(s.Text(), " ") | |
| if len(tokens) < 2 || (tokens[0] == "put" && len(tokens) != 3) { | |
| fmt.Println("invalid input") | |
| continue | |
| } | |
| switch tokens[0] { | |
| case "put": | |
| err := db.Put([]byte(tokens[1]), []byte(tokens[2]), nil) | |
| if err != nil { | |
| fmt.Println("failed to put data:", err) | |
| continue | |
| } | |
| case "get": | |
| value, err := db.Get([]byte(tokens[1]), nil) | |
| if err != nil { | |
| fmt.Println("failed to get value:", err) | |
| continue | |
| } | |
| fmt.Println(string(value)) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment