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

该文介绍了如何在fabric测试网络中使用GoSDK调用链码。首先确保在Windows环境下安装了正确的Go版本(不推荐1.1.9,建议1.17)。接着,下载并配置peer和orderorganization的目录到crypto-config。然后,创建config.yaml文件,定义组织、对等节点和策略。最后,通过示例的main函数展示如何创建SDK实例、获取通道客户端以及执行链码的查询和创建操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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/User1@org1.example.com/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\Admin@org1.example.com\msp\signcerts\Admin@org1.example.com-cert.pem
      User1:
        cert:
          path: D:\go\gocode\src\studentApp\crypto-config\peerOrganizations\org1.example.com\users\User1@org1.example.com\msp\signcerts\User1@org1.example.com-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/User1@org2.example.com/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\Admin@org2.example.com\msp\signcerts\Admin@org2.example.com-cert.pem
      User1:
        cert:
          path: D:\go\gocode\src\studentApp\crypto-config\peerOrganizations\org2.example.com\users\User1@org2.example.com\msp\signcerts\User1@org2.example.com-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/Admin@example.com/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))
}

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱写代码的大狼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值