gocb access to contents []byte in results.go in package gocb

273 Views Asked by At

Is there a was to access the []byte field of the Couchbase implementation in goLang or define a generic struct?

Use-case Not knowing the returned structure type at query time.

->Following code is not fully complete but should show what i'm doing<-

//two struct both share Id field
type Person struct {
    Id string `json:"id"`
    FirstName string `json:"firstName"`
}
type Building struct {
    Id string `json:"id"`
    Size int `json:"size"`
}
//sudo code for Couchbase connection, showing use of Default Connection
//edit 
import "github.com/couchbase/gocb/v2"
var dbCollection = cluster.Bucket(bucketName).DefaultCollection()

//show example get path variable from url eg /getFromDB/{id}
var pathVariables = mux.Vars(req)
id := pathVariables["id"]

//get request to db, and assign result to getResult, ignore error _
getResult, _ := dbCollection.Get(id, &gocb.GetOptions{})

//try and
dbPerson := Person{} //type is set to Person
getResult.Content(&dbPerson);

//If you print out the result, you see the content field as []bytes
// convert to string as **base 10 utf8** and you'll see the content; (minus a { at the start BUG?)
fmt.Printf("GetResult is: %+v\n",  *getResult)

//tried to get the result as bytes, to get the whole thing a map the content field later, but result is [123 125] or {
byteResult, errM := json.Marshal(*getResult)

//OR like, gives same output result [123 125] or { in base 10 utf8
var rawJson json.RawMessage
var errM error
rawJson, errM = json.Marshal(*getResult)

json.Unmarshal(rawBytes, &someStruct)

0

There are 0 best solutions below