Created
February 14, 2018 18:44
-
-
Save michielmulders/f15b69a812db28f586cfd26dfc4a6cbc to your computer and use it in GitHub Desktop.
Hyperledger Fabric getHistory Golang
This file contains 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
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()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
instead using buffer write, you can build an []interface{} and marshal into bytes. Can you change this code to that.