Last active
January 30, 2017 16:01
-
-
Save zegl/3c5a632a3b7a0ca8f504acb36c94984f to your computer and use it in GitHub Desktop.
A simple tutorial of how to use zegl/goriak with SetMap, GetMap, and Sets
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 ( | |
"gopkg.in/zegl/goriak.v3" | |
"errors" | |
"fmt" | |
) | |
// Initialize connection to Riak | |
func init() { | |
client, err := goriak.Connect(goriak.ConnectOpts{ | |
Address: "127.0.0.1", | |
}) | |
if err != nil { | |
panic(err) | |
} | |
r = client | |
} | |
// Our connection to Riak and the goriak library | |
var r *goriak.Session | |
func main() { | |
// Create a new task | |
// Initialize it with a Title and the Tag "shopping" | |
task := NewTask("task-1", "Buy Apples", []string{"shopping"}) | |
// Save the item to Riak | |
task.Save() | |
// Retreive the same task | |
get, err := GetTask("task-1") | |
if err != nil { | |
panic(err) | |
} | |
// Print what the Task contains | |
fmt.Printf("Task: %s\n", get.Title) | |
fmt.Printf("Tags: %+v\n", get.Tags.Strings()) | |
// Add one more tag and save the change to Riak | |
err = get.Tags.AddString("groceries").Exec(r) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("Retreive again from Riak:") | |
// Retreive the same task | |
get, err = GetTask("task-1") | |
if err != nil { | |
panic(err) | |
} | |
// Print what the Task contains | |
fmt.Printf("Task: %s\n", get.Title) | |
fmt.Printf("Tags: %+v\n", get.Tags.Strings()) | |
} | |
type Task struct { | |
Handle string | |
Title string | |
Tags *goriak.Set | |
} | |
// NewTask creates a new Task item | |
func NewTask(handle, title string, tags []string) *Task { | |
t := &Task{ | |
Handle: handle, | |
Title: title, | |
Tags: goriak.NewSet(), // It is important to initialize our Set if we want to use it | |
} | |
for _, tag := range tags { | |
t.Tags.AddString(tag) | |
} | |
return t | |
} | |
// Save uses SetMap from Riak to save everything in our Task object directly to RIak | |
func (t *Task) Save() { | |
_, err := goriak.Bucket("tasks", "maps").Set(t).Key(t.Handle).Run(r) | |
if err != nil { | |
panic(err) | |
} | |
} | |
// GetTask retreices a Task by handle | |
func GetTask(handle string) (*Task, error) { | |
t := Task{} | |
_, err := goriak.Bucket("tasks", "maps").Get(handle, &t).Run(r) | |
if err != nil { | |
return nil, errors.New("Could not get task from Riak: " + err.Error()) | |
} | |
return &t, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment