Skip to content

Instantly share code, notes, and snippets.

@lukebakken
Last active September 28, 2015 18:34
Show Gist options
  • Save lukebakken/df5ef740c82997957cba to your computer and use it in GitHub Desktop.
Save lukebakken/df5ef740c82997957cba to your computer and use it in GitHub Desktop.
Riak - Go client examples
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/gist-embed/2.2/gist-embed.min.js"></script>
</head>
<body>
<p>This is an example of embedding a gist using gist-embed.</p>
<p><code data-gist-id="df5ef740c82997957cba" data-gist-file="ex02.go" data-gist-hide-footer="true"></code></p>
<p>Pretty slick, huh?</p>
</body>
</html>
<html>
<body>
<p>This is an example of embedding a gist</p>
<p><script src="https://gist.github.com/lukebakken/df5ef740c82997957cba.js?file=ex01.go"></script></p>
</body>
</html>
package main
func intro_ex1_ping() {
client := BuildClient()
defer client.Stop()
success, perr := client.Ping()
CheckErr(perr)
if actual, expected := success, true; actual != expected {
ErrLog.Printf("[ERROR] got %v, expected %v", actual, expected)
} else {
Log.Printf("[INFO] ping result %v", success)
}
}
package main
import (
"encoding/json"
riak "github.com/basho/riak-go-client"
)
func intro_ex2_simple_app() {
client := BuildClient()
defer client.Stop()
monty_python := []string{
"Graham Chapman", "Eric Idle",
"Terry Gilliam", "Terry Jones",
"John Cleese", "Michael Palin",
}
j, jerr := json.Marshal(monty_python)
CheckErr(jerr)
object := &riak.Object{
ContentType: "application/json",
Value: j,
}
var cmd riak.Command
var err error
cmd, err = riak.NewStoreValueCommandBuilder().
WithBucket("ex2").
WithKey("Monty Python").
WithContent(object).
Build()
CheckErr(err)
err = client.Execute(cmd)
CheckErr(err)
cmd, err = riak.NewFetchValueCommandBuilder().
WithBucket("ex2").
WithKey("Monty Python").
Build()
CheckErr(err)
err = client.Execute(cmd)
CheckErr(err)
var fetched_pythons []string
fcmd := cmd.(*riak.FetchValueCommand)
val := fcmd.Response.Values[0].Value
err = json.Unmarshal(val, &fetched_pythons)
CheckErr(err)
JsonDump(fetched_pythons)
}
package main
import riak "github.com/basho/riak-go-client"
func intro_ex3_enable_search() {
client := BuildClient()
defer client.Stop()
var cmd riak.Command
var err error
cmd, err = riak.NewStoreIndexCommandBuilder().
WithIndexName("clients").
WithSchemaName("_yz_default").
Build()
CheckErr(err)
err = client.Execute(cmd)
CheckErr(err)
cmd, err = riak.NewStoreBucketPropsCommandBuilder().
WithBucket("coding-with-riak").
WithSearchIndex("clients").
Build()
CheckErr(err)
err = client.Execute(cmd)
CheckErr(err)
cmd, err = riak.NewFetchBucketPropsCommandBuilder().
WithBucket("coding-with-riak").
Build()
CheckErr(err)
err = client.Execute(cmd)
CheckErr(err)
fcmd := cmd.(*riak.FetchBucketPropsCommand)
resp := fcmd.Response
Log.Println("[ex03] coding-with-riak bucket search index:", resp.SearchIndex)
}
package main
import (
"encoding/json"
"time"
riak "github.com/basho/riak-go-client"
)
type ClientInfo struct {
Name_s string
Maintainer_s string
Popular_b bool
key string
}
func intro_ex4_do_search() {
client := BuildClient()
defer client.Stop()
var cmd riak.Command
var err error
clients := []ClientInfo{
{"Ruby Client", "Basho", true, "ruby"},
{"Go Client", "Basho", true, "go"},
}
for _, c := range clients {
cj, jerr := json.Marshal(c)
CheckErr(jerr)
obj := &riak.Object{
ContentType: "application/json",
Charset: "utf-8",
Value: cj,
}
cmd, err = riak.NewStoreValueCommandBuilder().
WithBucket("coding-with-riak").
WithKey(c.key).
WithContent(obj).
Build()
CheckErr(err)
err = client.Execute(cmd)
CheckErr(err)
}
cmd, err = riak.NewSearchCommandBuilder().
WithIndexName("clients").
WithQuery("Maintainer_s:Basho").
Build()
CheckErr(err)
time.Sleep(time.Second * 2)
err = client.Execute(cmd)
CheckErr(err)
scmd := cmd.(*riak.SearchCommand)
Log.Println("[ex04] NumFound:", scmd.Response.NumFound)
}
package main
import (
"encoding/json"
"time"
riak "github.com/basho/riak-go-client"
)
func intro_ex5_do_search() {
client := BuildClient()
defer client.Stop()
var cmd riak.Command
var err error
clientInfo := ClientInfo{"Python Client", "Basho", true, "python"}
cj, jerr := json.Marshal(clientInfo)
CheckErr(jerr)
obj := &riak.Object{
ContentType: "application/json",
Charset: "utf-8",
Value: cj,
}
cmd, err = riak.NewStoreValueCommandBuilder().
WithBucket("coding-with-riak").
WithKey(clientInfo.key).
WithContent(obj).
Build()
CheckErr(err)
err = client.Execute(cmd)
CheckErr(err)
cmd, err = riak.NewSearchCommandBuilder().
WithIndexName("clients").
WithQuery("Maintainer_s:Basho").
Build()
CheckErr(err)
time.Sleep(time.Second * 2)
err = client.Execute(cmd)
CheckErr(err)
scmd := cmd.(*riak.SearchCommand)
for _, doc := range scmd.Response.Docs {
Log.Printf("%s, %s", doc.Fields["Name_s"][0], doc.Fields["Maintainer_s"][0])
}
}
package main
import (
"errors"
"os"
)
func main() {
if len(os.Args) < 2 {
ErrExit(errors.New("must be run with one argument"))
}
switch os.Args[1] {
case "intro":
Log.Println("running Intro to Riak KV examples")
intro_ex1_ping()
intro_ex2_simple_app()
intro_ex3_enable_search()
intro_ex4_do_search()
intro_ex5_do_search()
case "docs":
Log.Println("running Basho Docs examples")
}
}
@echo off
setlocal
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "%~dp0\make.ps1" %*
exit /b %ERRORLEVEL%
<#
.SYNOPSIS
Powershell script to run Intro to Riak KV for Go on Windows
.DESCRIPTION
This script will run 'go' correctly depending on parameters passed to this script.
.PARAMETER Target
Target to build. Can be one of the following:
* Format - run *.go files through 'go fmt'
* Run - Run all examples
* Intro - Run "Intro to Riak KV" examples
* Docs - Run Basho Docs examples
.PARAMETER Verbose
Use to increase verbosity.
.EXAMPLE
C:\Users\Bashoman> cd $env:GOPATH\src
C:\Users\Bashoman> git clone -o intro-riak-kv git@gist.github.com:df5ef740c82997957cba.git
C:\Users\Bashoman> cd intro-riak-kv
C:\Users\Bashoman\go\src\intro-riak-kv>.\make.ps1 -Target Run -Verbose
.NOTES
Author: Luke Bakken
Date: August 26, 2015
#>
[CmdletBinding()]
Param(
[Parameter(Mandatory=$False, Position=0)]
[ValidateSet('Format', 'Run', 'Intro', 'Docs', IgnoreCase = $True)]
[string]$Target = 'Run'
)
Set-StrictMode -Version Latest
$package = 'riak-go-examples'
$IsDebug = $DebugPreference -ne 'SilentlyContinue'
$IsVerbose = $VerbosePreference -ne 'SilentlyContinue'
# Note:
# Set to Continue to see DEBUG messages
if ($IsVerbose) {
$DebugPreference = 'Continue'
}
trap
{
Write-Error -ErrorRecord $_
exit 1
}
function Get-ScriptPath {
$scriptDir = Get-Variable PSScriptRoot -ErrorAction SilentlyContinue | ForEach-Object { $_.Value }
if (!$scriptDir) {
if ($MyInvocation.MyCommand.Path) {
$scriptDir = Split-Path $MyInvocation.MyCommand.Path -Parent
}
}
if (!$scriptDir) {
if ($ExecutionContext.SessionState.Module.Path) {
$scriptDir = Split-Path (Split-Path $ExecutionContext.SessionState.Module.Path)
}
}
if (!$scriptDir) {
$scriptDir = $PWD
}
return $scriptDir
}
function Execute($cmd, $argz) {
Write-Verbose "$cmd $argz"
& $cmd $argz
if ($? -ne $True) {
throw "'$cmd $argz' failed: $LastExitCode"
}
Write-Debug "'$cmd $argz' exit code: $LastExitCode"
}
function Do-Format {
$script_path = Get-ScriptPath
$cmd = 'gofmt'
$argz = '-s', '-w', $script_path
Execute $cmd $argz
}
function Do-InstallDeps {
$cmd = 'go.exe'
$argz = 'get', '-t', './...'
Execute $cmd $argz
}
function Do-Vet {
$cmd = 'go.exe'
$script_path = Get-ScriptPath
$argz = 'tool', 'vet', '-shadow=true', '-shadowstrict=true', $script_path
Execute $cmd $argz
$argz = 'vet', "$package/..."
Execute $cmd $argz
}
function Do-Run-Intro {
$cmd = 'go.exe'
$argz = 'run', 'main.go', 'util.go', 'intro-ex01.go', 'intro-ex02.go', 'intro-ex03.go', 'intro-ex04.go', 'intro-ex05.go', 'intro'
Execute $cmd $argz
}
function Do-Run-Docs {
$cmd = 'go.exe'
$argz = 'run', 'main.go', 'util.go', 'docs'
Execute $cmd $argz
}
function Do-Run {
Do-Run-Intro
Do-Run-Docs
}
Write-Debug "Target: $Target"
switch ($Target)
{
'Format' { Do-Format }
'Intro' { Do-InstallDeps; Do-Vet; Do-Run-Intro; }
'Docs' { Do-InstallDeps; Do-Vet; Do-Run-Docs; }
'Run' { Do-InstallDeps; Do-Vet; Do-Run; }
default { throw "Unknown target: $Target" }
}
exit 0
.PHONY: all install-deps lint run
PROJDIR = $(realpath $(CURDIR))
RUNCMD = go run $(wildcard *.go)
all: install-deps lint run
install-deps:
go get -t ./...
lint: install-deps
go tool vet -shadow=true -shadowstrict=true $(PROJDIR)
go vet ./...
fmt:
gofmt -s -w $(PROJDIR)
run: run-intro-examples run-docs-examples
run-intro-examples: lint
$(RUNCMD) intro
run-docs-examples: lint
$(RUNCMD) docs
package main
import (
"encoding/json"
"fmt"
"log"
"os"
"strconv"
"time"
riak "github.com/basho/riak-go-client"
)
const iso8601format = "2006-01-02T15:04:05"
var Log = log.New(os.Stdout, "", log.LstdFlags)
var ErrLog = log.New(os.Stderr, "", log.LstdFlags)
func Iso8601(t time.Time) string {
return t.Format(iso8601format)
}
func CheckErr(err error) {
if err != nil {
ErrExit(err)
}
}
func ErrExit(err error) {
ErrLog.Println(err)
os.Exit(1)
}
func GetRiakPort() uint16 {
riakPort := uint16(10017)
if portEnvVar := os.ExpandEnv("$RIAK_PORT"); portEnvVar != "" {
if portNum, err := strconv.Atoi(portEnvVar); err == nil {
riakPort = uint16(portNum)
}
}
return riakPort
}
func GetRiakHost() string {
riakHost := "riak-test"
if hostEnvVar := os.ExpandEnv("$RIAK_HOST"); hostEnvVar != "" {
riakHost = hostEnvVar
}
return riakHost
}
func GetRiakAddress() string {
return fmt.Sprintf("%s:%d", GetRiakHost(), GetRiakPort())
}
func GetRiakAddresses() []string {
// Assume that a 4-node devrel is being used where PB port numbers
// increase by 10
host := GetRiakHost()
basePort := GetRiakPort()
count := uint16(4)
addrs := make([]string, count)
for i := uint16(0); i < count; i++ {
port := basePort + (i * 10)
addrs[i] = fmt.Sprintf("%s:%d", host, port)
}
return addrs
}
func BuildClient() *riak.Client {
opts := &riak.NewClientOptions{
RemoteAddresses: GetRiakAddresses(),
}
client, err := riak.NewClient(opts)
CheckErr(err)
return client
}
func JsonDump(val interface{}) {
if val == nil {
Log.Println("[JsonDump]", "NIL VAL")
} else {
if json, err := json.MarshalIndent(val, "", " "); err != nil {
ErrLog.Printf("[JsonDump ERROR] %s", err.Error())
} else {
Log.Println(string(json))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment