Skip to content

Instantly share code, notes, and snippets.

@michielmulders
Created February 14, 2018 18:44
Show Gist options
  • Save michielmulders/f15b69a812db28f586cfd26dfc4a6cbc to your computer and use it in GitHub Desktop.
Save michielmulders/f15b69a812db28f586cfd26dfc4a6cbc to your computer and use it in GitHub Desktop.
Hyperledger Fabric getHistory Golang
func (t *SimpleChaincode) getHistoryForMarble(stub shim.ChaincodeStubInterface, args []string) sc.Response {
if len(args) < 1 {
return shim.Error("Incorrect number of arguments. Expecting 1")
}
marbleName := args[0]
fmt.Printf("- start getHistoryForMarble: %s\n", marbleName)
resultsIterator, err := stub.GetHistoryForKey(marbleName)
if err != nil {
return shim.Error(err.Error())
}
defer resultsIterator.Close()
// buffer is a JSON array containing historic values for the marble
var buffer bytes.Buffer
buffer.WriteString("[")
bArrayMemberAlreadyWritten := false
for resultsIterator.HasNext() {
response, err := resultsIterator.Next()
if err != nil {
return shim.Error(err.Error())
}
// Add a comma before array members, suppress it for the first array member
if bArrayMemberAlreadyWritten == true {
buffer.WriteString(",")
}
buffer.WriteString("{\"TxId\":")
buffer.WriteString("\"")
buffer.WriteString(response.TxId)
buffer.WriteString("\"")
buffer.WriteString(", \"Value\":")
// if it was a delete operation on given key, then we need to set the
//corresponding value null. Else, we will write the response.Value
//as-is (as the Value itself a JSON marble)
if response.IsDelete {
buffer.WriteString("null")
} else {
buffer.WriteString(string(response.Value))
}
buffer.WriteString(", \"Timestamp\":")
buffer.WriteString("\"")
buffer.WriteString(time.Unix(response.Timestamp.Seconds, int64(response.Timestamp.Nanos)).String())
buffer.WriteString("\"")
buffer.WriteString(", \"IsDelete\":")
buffer.WriteString("\"")
buffer.WriteString(strconv.FormatBool(response.IsDelete))
buffer.WriteString("\"")
buffer.WriteString("}")
bArrayMemberAlreadyWritten = true
}
buffer.WriteString("]")
fmt.Printf("- getHistoryForMarble returning:\n%s\n", buffer.String())
return shim.Success(buffer.Bytes())
}
@mrvijaycode
Copy link

instead using buffer write, you can build an []interface{} and marshal into bytes. Can you change this code to that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment