main.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "time"
  6. raft_client "igit.com/xbase/raft/client"
  7. )
  8. func main() {
  9. // 1. Create a new client instance
  10. // Ensure your Raft server is running on this address
  11. client := raft_client.NewClient("127.0.0.1:9011")
  12. // 2. Connect to the server
  13. fmt.Println("Connecting to server...")
  14. if err := client.Connect(); err != nil {
  15. log.Fatalf("Failed to connect: %v", err)
  16. }
  17. defer client.Close()
  18. // 3. Login
  19. // Default credentials for the example server
  20. username := "root"
  21. password := "11111"
  22. fmt.Printf("Logging in as %s...\n", username)
  23. token, err := client.Login(username, password)
  24. if err != nil {
  25. log.Printf("Login failed: %v", err)
  26. log.Println("Attempting to use SYSTEM_INTERNAL bypass (Development Mode)...")
  27. if err := client.Auth("SYSTEM_INTERNAL"); err != nil {
  28. log.Fatalf("Bypass failed: %v. Please reset data/node1 or check credentials.", err)
  29. }
  30. fmt.Println("Bypass successful! using SYSTEM_INTERNAL token.")
  31. } else {
  32. fmt.Printf("Login successful! Token: %s\n", token)
  33. }
  34. // 4. Set a value
  35. key := "demo_key"
  36. value := "Hello Raft Client! " + time.Now().Format(time.RFC3339)
  37. fmt.Printf("Setting key '%s' to '%s'...\n", key, value)
  38. if err := client.Set(key, value); err != nil {
  39. log.Fatalf("Set failed: %v", err)
  40. }
  41. fmt.Println("Set successful.")
  42. // 5. Get the value back
  43. fmt.Printf("Getting key '%s'...\n", key)
  44. gotVal, err := client.Get(key)
  45. if err != nil {
  46. log.Fatalf("Get failed: %v", err)
  47. }
  48. fmt.Printf("Got value: %s\n", gotVal)
  49. // 6. Verify
  50. if gotVal == value {
  51. fmt.Println("Verification successful: Value matches!")
  52. } else {
  53. fmt.Printf("Verification failed: Expected '%s', got '%s'\n", value, gotVal)
  54. }
  55. // 7. Async Set Example (High Performance)
  56. fmt.Println("\nTesting Async Set (ASET)...")
  57. asyncKey := "async_demo_key"
  58. asyncVal := "Async Value"
  59. if err := client.SetAsync(asyncKey, asyncVal); err != nil {
  60. log.Fatalf("Async Set failed: %v", err)
  61. }
  62. // Wait a tiny bit for replication (since it's async, it might take a ms to be consistent if reading immediately from same node)
  63. time.Sleep(10 * time.Millisecond)
  64. gotAsyncVal, err := client.Get(asyncKey)
  65. if err != nil {
  66. log.Fatalf("Get Async Key failed: %v", err)
  67. }
  68. fmt.Printf("Got async value: %s\n", gotAsyncVal)
  69. }