2014-11-27

How to use Go-Couchbase

Today I will try to use Go-Couchbase, to insert, fetch, update and delete from database. To install go-couchbase, type this commands:

go get -u -v github.com/couchbaselabs/go-couchbase

Then just create an example source code and run it:

package main

import (
"fmt"

"github.com/couchbaselabs/go-couchbase"
//"github.com/davecgh/go-spew/spew"
"encoding/json"

"github.com/kr/pretty"
//"reflect"
"errors"
"runtime"
"strings"
)

var FILE_PATH string
var CB *couchbase.Bucket

// initialize file path
func init() {
_, file, _, _ := runtime.Caller(1)
FILE_PATH = file[:4+strings.Index(file, "/src/")]
err := errors.New("no error")
CB, err = couchbase.GetBucket("http://127.0.0.1:8091/", "default", "default")
Panic(err, "Error connection, getting pool or bucket:  %v")
}

// print warning message
func Check(err error, msg string, args ...interface{}) error {
if err != nil {
_, file, line, _ := runtime.Caller(1)
str := fmt.Sprintf("%s:%d: ", file[len(FILE_PATH):], line)
fmt.Errorf(str+msg, args...)
res := pretty.Formatter(err)
fmt.Errorf("%# v\n", res)
}
return err
}

// print error message and exit program
func Panic(err error, msg string, args ...interface{}) {
if Check(err, msg, args...) != nil {
panic(err)
}
}

// describe a variable
func Explain(args ...interface{}) {
_, file, line, _ := runtime.Caller(1)
//res, _ := json.MarshalIndent(variable, "   ", "  ")
for _, arg := range args {
res := pretty.Formatter(arg)
fmt.Printf("%s:%d: %# v\n", file[len(FILE_PATH):], line, res)
}
//spew.Dump(variable)
}

func main() {

var err error

// save values (upsert)
err = CB.Set("someKey", 0, []string{"an", "example", "list"})
Check(err, "failed to set somekey")

err = CB.Set("primaryKey", 0, 1)
Check(err, "failed to set primaryKey")

// fetch one value
var rv interface{}
err = CB.Get("someKey", &rv)
Check(err, "failed to get someKey")
Explain(rv)

// fetch with CheckAndSet id
cas := uint64(0)
err = CB.Gets("primaryKey", &rv, &cas)
Check(err, "failed to get primaryKey")
Explain(cas, rv)

// fetch multivalue
rows, err := CB.GetBulk([]string{"someKey", "primaryKey", "nothingKey"})
Check(err, "failed to get someKey or primaryKey or nothingKey")
Explain(rows)

jsonStr := rows["someKey"].Body
Explain(string(jsonStr))

stringList := []string{}
err = json.Unmarshal(jsonStr, &stringList)
Check(err, "failed to convert back to json")
Explain(stringList)

// increment value, returns new value
nv, err := CB.Incr("primaryKey", 1, 1, 0)
Check(err, "failed to increment primaryKey")
Explain(nv)

// increment value, defaults to 1 if not exists
nv, err = CB.Incr("key3", 1, 1, 60)
Check(err, "failed to increment primaryKey")
Explain(nv)

}

This would give an output:

/test.go:92: []interface {}{
    "an",
    "example",
    "list",
}
/test.go:98: uint64(0x13aa8b32b9f7f091)
/test.go:98: float64(1)
/test.go:103: map[string]*gomemcached.MCResponse{
    "primaryKey": &gomemcached.MCResponse{
        Opcode: 0x0,
        Status: 0x0,
        Opaque: 0x0,
        Cas:    0x13aa8b32b9f7f091,
        Extras: {0x0, 0x0, 0x0, 0x0},
        Key:    {},
        Body:   {0x31},
        Fatal:  false,
    },
    "someKey": &gomemcached.MCResponse{
        Opcode: 0x0,
        Status: 0x0,
        Opaque: 0x0,
        Cas:    0x13aa8b32b9e4690f,
        Extras: {0x0, 0x0, 0x0, 0x0},
        Key:    {},
        Body:   {0x5b, 0x22, 0x61, 0x6e, 0x22, 0x2c, 0x22, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x22, 0x2c, 0x22, 0x6c, 0x69, 0x73, 0x74, 0x22, 0x5d},
        Fatal:  false,
    },
}
/test.go:106: "[\"an\",\"example\",\"list\"]"
/test.go:111: []string{"an", "example", "list"}
/test.go:116: uint64(0x2)
/test.go:121: uint64(0x4)

No comments :

Post a Comment

THINK: is it True? is it Helpful? is it Inspiring? is it Necessary? is it Kind?