我正在尝试编写一个简单的链码,它使用结构来存储客户详细信息。我有一套可以正常工作的详细信息功能。我希望编写另一个 getDetails 函数,它将 UID 作为参数并使用该 UID 打印客户的详细信息。需要帮助!
package main
import (
"errors"
"fmt"
"github.com/hyperledger/fabric/core/chaincode/shim"
)
type Customer struct {
UID string
Name string
Address struct {
StreetNo string
Country string
}
}
type SimpleChaincode struct {
}
func (t *SimpleChaincode) Init(stub shim.ChaincodeStubInterface) ([]byte, error) {
fmt.Printf("initialization done!!!")
fmt.Printf("initialization done!!!")
return nil, nil
}
func (t *SimpleChaincode) setDetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
if len(args) < 3 {
return nil, errors.New("insert Into Table failed. Must include 3 column values")
}
customer := &Customer{}
customer.UID = args[0]
customer.Name = args[1]
customer.Address.Country = args[2]
return nil, nil
}
func (t *SimpleChaincode) getDetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
//wish to print all details of an particular customer corresponding to the UID
return nil, nil
}
func (t *SimpleChaincode) Invoke(stub shim.ChaincodeStubInterface) ([]byte, error) {
function, args := stub.GetFunctionAndParameters()
fmt.Printf("Inside Invoke %s", function)
if function == "setDetails" {
return t.setDetails(stub, args)
} else if function == "getDetails" {
return t.getDetails(stub, args)
}
return nil, errors.New("Invalid invoke function name. Expecting "query"")
}
func main() {
err := shim.Start(new(SimpleChaincode))
if err != nil {
fmt.Printf("Error starting Simple chaincode: %s", err)
}
}
直到
现在我才知道Hyperledger,但是在查看了github文档之后,我发现您会使用stub.PutState
来存储您的客户信息,然后使用stub.GetState
将其取回。
由于这两种方法都请求字节切片,我的猜测是这样的:
func (t *SimpleChaincode) setDetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
if len(args) < 3 {
return nil, errors.New("insert Into Table failed. Must include 3 column values")
}
customer := &Customer{}
customer.UID = args[0]
customer.Name = args[1]
customer.Address.Country = args[2]
raw, err := json.Marshal(customer)
if err != nil {
return nil, err
}
err := stub.PuState(customer.UID, raw)
if err != nil {
return nil, err
}
return nil, nil
}
func (t *SimpleChaincode) getDetails(stub shim.ChaincodeStubInterface, args []string) ([]byte, error) {
if len(args) != 1 {
return nil, errors.New("Incorrect number of arguments. Expecting name of the key to query")
}
return stub.GetState(args[0])
}