使用go-sdk调用链码,以测试网络为例2.4.1版本

使用go-sdk调用链码,以测试网络为例

前置-需要在 fabric测试网络中成功安装链码,如果没有安装,可以先看这篇进行安装fabric2.4.1安装链码
windows机器上go的版本不能是1.1.9会出现异常错误,可以使用1.17版本
此篇文章仅仅是作为可以把测试网络安装的go链码跑通的例子

第一步 创建项目 从测试网络中下载peerorganization和orderorganization目录文件

将下载好的文件合并放到crypto-config目录下,放到项目的根目录下即可
在这里插入图片描述

第二步 导入config.ymal文件

编写config模板,根据自己的目录和IP进行对应,放到根目录下


version: 1.0.0

client:

  organization: org1

  logging:
    level: info

  cryptoconfig:
    path: #D:/go/gocode/src/studentApp/crypto-config


channels:

  # multi-org test channel
  mychannel:
    peers:
      peer0.org1.example.com:
        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true

      peer1.org1.example.com:
        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true

      peer0.org2.example.com:
        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true

      peer1.org2.example.com:
        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true

    policies:
      queryChannelConfig:
        minResponses: 1
        maxTargets: 1
        retryOpts:
          attempts: 5
          initialBackoff: 500ms
          maxBackoff: 5s
          backoffFactor: 2.0
#
# list of participating organizations in this network
#
organizations:
  org1:
    mspid: Org1MSP

    # This org's MSP store (absolute path or relative to client.cryptoconfig)
    cryptoPath:  D:/go/gocode/src/studentApp/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp

    peers:
      - peer0.org1.example.com
      - peer1.org1.example.com
    Admin:
      cert:
        path: D:\go\gocode\src\studentApp\crypto-config\peerOrganizations\org1.example.com\users\[email protected]\msp\signcerts\[email protected]-cert.pem
      User1:
        cert:
          path: D:\go\gocode\src\studentApp\crypto-config\peerOrganizations\org1.example.com\users\[email protected]\msp\signcerts\[email protected]-cert.pem

  org2:
    mspid: Org2MSP

    # This org's MSP store (absolute path or relative to client.cryptoconfig)
    cryptoPath:  D:/go/gocode/src/studentApp/crypto-config/peerOrganizations/org2.example.com/users/[email protected]/msp

    peers:
      - peer0.org2.example.com
      - peer1.org2.example.com
    users:
      Admin:
        cert:
          path: D:\go\gocode\src\studentApp\crypto-config\peerOrganizations\org2.example.com\users\[email protected]\msp\signcerts\[email protected]-cert.pem
      User1:
        cert:
          path: D:\go\gocode\src\studentApp\crypto-config\peerOrganizations\org2.example.com\users\[email protected]\msp\signcerts\[email protected]-cert.pem

  # Orderer Org name
  ordererorg:
    # Membership Service Provider ID for this organization
    mspID: OrdererMSP

    # Needed to load users crypto keys and certs for this org (absolute path or relative to global crypto path, DEV mode)
    cryptoPath: D:/go/gocode/src/studentApp/crypto-config/ordererOrganizations/example.com/users/[email protected]/msp

orderers:

  orderer.example.com:
    # [Optional] Default: Infer from hostname
    url: orderer.example.com:7050

    grpcOptions:
      ssl-target-name-override: orderer.example.com
      keep-alive-time: 0s
      keep-alive-timeout: 20s
      keep-alive-permit: false
      fail-fast: false
      allow-insecure: false

    tlsCACerts:
      # Certificate location absolute path
      path: D:/go/gocode/src/studentApp/crypto-config/ordererOrganizations/example.com/tlsca/tlsca.example.com-cert.pem

peers:


  peer0.org1.example.com:
    # this URL is used to send endorsement and query requests
    # [Optional] Default: Infer from hostname
    url: peer0.org1.example.com:7051
    grpcOptions:
      ssl-target-name-override: peer0.org1.example.com
      # These parameters should be set in coordination with the keepalive policy on the server,
      # as incompatible settings can result in closing of connection.
      # When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
      keep-alive-time: 0s
      keep-alive-timeout: 20s
      keep-alive-permit: false
      fail-fast: false
      # allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
      allow-insecure: false
    #grpcOptions:
    #  ssl-target-name-override: peer0.org1.example.com

    tlsCACerts:
      # Certificate location absolute path
      path: D:/go/gocode/src/studentApp/crypto-config/peerOrganizations/org1.example.com/tlsca/tlsca.org1.example.com-cert.pem



  peer0.org2.example.com:
    url: peer0.org2.example.com:9051
    #grpcOptions:
    #  ssl-target-name-override: peer0.org2.example.com
    grpcOptions:
      ssl-target-name-override: peer0.org2.example.com
      # These parameters should be set in coordination with the keepalive policy on the server,
      # as incompatible settings can result in closing of connection.
      # When duration of the 'keep-alive-time' is set to 0 or less the keep alive client parameters are disabled
      keep-alive-time: 0s
      keep-alive-timeout: 20s
      keep-alive-permit: false
      fail-fast: false
      # allow-insecure will be taken into consideration if address has no protocol defined, if true then grpc or else grpcs
      allow-insecure: false
    tlsCACerts:
      path: D:/go/gocode/src/studentApp/crypto-config/peerOrganizations/org2.example.com/tlsca/tlsca.org2.example.com-cert.pem

第三步 ,编写main函数

package main

import (
	"fmt"
	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
	"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

func main() {
    
    
	// 创建 SDK 实例
	sdk, err := fabsdk.New(config.FromFile("config.yaml"))
	if err != nil {
    
    
		fmt.Printf("failed to create SDK instance: %s\n", err)
		return
	}
	defer sdk.Close()

	// 获取通道客户端
	clientChannelContext := sdk.ChannelContext("mychannel", fabsdk.WithUser("User1"), fabsdk.WithOrg("Org1"))
	channelClient, err := channel.New(clientChannelContext)
	if err != nil {
    
    
		fmt.Printf("failed to create channel client: %s\n", err)
		return
	}

	// 构建链码调用请求
	//查询数据
	QueryStudent := channel.Request{
    
    
		ChaincodeID: "studentcontract",
		Fcn:         "QueryStudent",
		Args:        [][]byte{
    
    []byte("1")},
	}
	// 发送链码调用请求
	response, err := channelClient.Execute(QueryStudent)
	if err != nil {
    
    
		fmt.Printf("failed to call chaincode: %s\n", err)
		return
	}

	fmt.Printf("response payload: %s\n", string(response.Payload))
	//增加学生
	CreateStudent := channel.Request{
    
    
		ChaincodeID: "studentcontract",
		Fcn:         "CreateStudent",
		Args:        [][]byte{
    
    []byte("3"), []byte("ww"), []byte("28"), []byte("周口")},
	}
	res, err := channelClient.Execute(CreateStudent)
	fmt.Printf("response payload: %s\n", string(res.Payload))

	//查询全部学生
	queryAllStudent := channel.Request{
    
    
		ChaincodeID: "studentcontract",
		Fcn:         "QueryAllStudents",
		Args:        [][]byte{
    
    },
	}
	execute, err := channelClient.Execute(queryAllStudent)
	if err!=nil {
    
    
		fmt.Printf("failed to call chaincode: %s\n", err)
	}
	fmt.Printf("response payload: %s\n", string(execute.Payload))
}

如果使用的是自己的链码,根据自己链码的实际情况进行修改即可

猜你喜欢

转载自blog.csdn.net/zhangmingfie/article/details/129613198