Chaincode函数显示结构值

时间:2017-01-23 10:00:40

标签: go blockchain hyperledger hyperledger-fabric

我试图编写一个使用结构存储客户详细信息的简单链代码。我有一个setDetails func工作正常。我希望编写另一个getDetails func,它将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)
    }
}

1 个答案:

答案 0 :(得分:1)

到目前为止我还不知道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])
}