Tag Archives: Go

[Solved] Fabric_sdk_go:QueryBlockConfig failed: QueryBlockConfig failed: target(s) required

Fabric_sdk_go:[Solved]event service creation failed: could not get chConfig cache reference: QueryBlockConfig failed: QueryBlockConfig failed: target(s) required
Error Message:

Configuration file config_test: channel name is mychannel, in the demo it is orgchannel.
[Solution] Comment out orgchannel in config_test:

  # Mychannel overrides initialBackoff for discovery
  mychannel:
    policies:
      discovery:
        retryOpts:
          #[Required for override] number of retry attempts
          attempts: 4
          initialBackoff: 1s

  # multi-org test channel
  # orgchannel:  //remove

    # orderers:
    #  - orderer.example.com

    peers:
      peer0.org1.example.com:
        endorsingPeer: true
        chaincodeQuery: true
        ledgerQuery: true
        eventSource: true

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

Problem-solving:

How to Solve golang test Error: # command-line-arguments [command-line-arguments.test]

Project scenario:

xxx.go xxx_unit test and code of test.go are open. The code is not in gopath and the project root set by idea.

Background:

Gopath:/users/ZYJ/go project root:/users/ZYJ/study/demogo source file:/users/ZYJ/study/demo/go/SRC/xxx_ test.go


Problem Description:

xxx.go xxx_test.go is stored separately   xxx_test.go compilation error

command-line-arguments [command-line-arguments.test]

Cause analysis:

Go test XXX executed by golang IDE_test.go runs as file by default and does not import dependent files. You need to actively import dependencies

Usually: the project is in gopath or project root directory, and the dependency can be found normally


Solution:

go test -v xxxx.go xxxx_test.go

Golang ide multiple selections for quick operation

[Solved] panic: runtime error: invalid memory address or nil pointer dereference

Error code:

type MongoConn struct {
	clientOptions *options.ClientOptions
	client        *mongo.Client
	collections   *mongo.Collection
}

var mongoConn *MongoConn

func InitMongoConn() error{

	ctx, cancelFunc := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancelFunc()

	mongoUrl := "mongodb://" + user + ":" + password + "@" + url + "/" + dbname
	mongoConn.clientOptions = options.Client().ApplyURI(mongoUrl)
	
	//......
}

To solve the problem caused by pointer assignment:

var mongoConn MongoConn

[go] error prompt proto. Unmarshal: missing method protoreflect

Problem: an error is reported when proto unmarshal is used, and the following information is prompted:

cannot use promoRule (variable of type *db.PromotionRuleSet) as protoreflect.ProtoMessage value in argument to proto.Unmarshal: missing method ProtoReflect (compile)

Solution:
Import package from

"google.golang.org/protobuf/proto"

Change to

"github.com/golang/protobuf/proto"

[Solved] ambiguous import: found package github.com/spf13/cobra/cobra in multiple modules

Quoted articles: https://stackoverflow.com/questions/63710830/spf13-cobra-cant-download-binary-to-gopath-bin

When the package is managed by go mod, it will be downloaded to $gopath/PKG/mod.

When downloading cobra, the executable binary Cobra will be automatically created in the $gopath/bin directory. If the following command line ~ /. Bashrc is added, cobra can be automatically referenced as a command line tool:

export PATH=$PATH:$GOROOT/bin:$GOPATH/bin

However, an error is reported in go get github.com/spf13/cobra/cobra: ambiguous import: found package github.com/spf13/cobra/cobra in multiple modules, indicating that duplicate packages exist. At this time, the solution is to set the version value. The replacement installation command is as follows:

go get -u github.com/spf13/cobra/[email protected]

Json: struct field readyReplicas has json tag but is not exported [How to Solve]

type MeshStatus struct {
	// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
	// Important: Run "make" to regenerate code after modifying this file
	AvailableReplicas int `json:"available_replicas,omitempty"`
	readyReplicas     int `json:"ready_replicas,omitempty"`
	Replicas          int `json:"replicas,omitempty"`
}

error: struct field readyReplicas has json tag but is not exported
Cause of the error readyReplicas does not have a capitalization at the beginning ReadyReplicas

Go compiles the EXE executable to remove the CMD window at run time

         Recently, I started to contact go language again and wrote an EXE executable program. However, such a console window will appear every time I execute it, and there is no content yet. It’s not elegant, of course.

We can solve this problem by setting compilation parameters in go build

go build -ldflags "-s -w -H=windowsgui"

-s Omit the symbol table and debug information
-w Omit the DWARF symbol table Omit the DWARF symbol table
-H windowsgui does not print messages to the console (On Windows, -H windowsgui writes a "GUI binary" instead of a "console binary."), so there is no cmd window

In this way, the EXE program generated by go compilation can run in the background.

How to Add custom middleware for GRPC server

1. Objective:

a. To customize a middleware to capture global code 500 error (panic error) in grpc server.

b. Grpc middleware is different from HTTP gin middleware. Gin can use use use or handlerfunc to enable middleware, but grpc can’t. Here we use the go grpc middleware plug-in to demonstrate.

c. Grpc client is only an active calling interface, so it is unnecessary to be a middleware.

2. Writing middleware

Install plug-in dependencies:

go get github.com/grpc-ecosystem/go-grpc-middleware

All the codes of middleware, in which the return value type is fixed (the return value form of go grpc middleware plug-in is the maximum value form)

package middlewares

import (
	"context"
	"fmt"

	"google.golang.org/grpc"
)


// StreamGSError500 Catching Fatal Errors in Streaming Code
func StreamGSError500(address string) grpc.StreamServerInterceptor {
	return func(srv interface{}, stream grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) (err error) {
		
		fmt.Println("StreamGSError500 The service has been added to the listener===")
		defer func() {
			if err := recover(); err != nil {
				//Print error stack information
				fmt.Println(err)
				
			}
		}()

		err = handler(srv, stream)
		return err
	}
}

// UnaryGSError500 Catching fatal errors in simple code
func UnaryGSError500(address string) grpc.UnaryServerInterceptor {
	return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (_ interface{}, err error) {

		fmt.Println("UnaryGSError500 The service has been added to the listener===")
		defer func() {
			if err := recover(); err != nil {
				//Print error stack information
				fmt.Println(err)
				
			}
		}()

		resp, err := handler(ctx, req)
		return resp, err
	}
}

3. Add middleware when starting grpc server

introduce:

import (
    "github.com/grpc-ecosystem/go-grpc-middleware"
	grpcRecovery "github.com/grpc-ecosystem/go-grpc-middleware/recovery"
	"google.golang.org/grpc"

)

Startup:

    var address string = "127.0.0.1:9600"


	// Instantiate the grpc server and insert the median price
	grpcServer := grpc.NewServer(
		grpc.StreamInterceptor(grpc_middleware.ChainStreamServer( // Stream Interceptor
			middlewares.StreamGSError500(address),
            grpcRecovery.StreamServerInterceptor(),
		)),
		grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer( // Simple Interceptor
			middlewares.UnaryGSError500(address),
            grpcRecovery.StreamServerInterceptor(),
		)),
	)

Git Pull Error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errfno 10054

The following error occurs when git pull

error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errfno 10054
fatal: The remote end hung up unexpectedly
fatal: early EOF
fatal: unpack-objects failed

Execute the pull command again after the following Settings

git config http.postBuffer 524288000

This command sets the size of the communication cache. The previous error was caused by too much synchronized data.
The config parameters here can be seen in the config file in the file directory

[core]
	repositoryformatversion = 0
	filemode = false
	bare = false
	logallrefupdates = true
	symlinks = false
	ignorecase = true
[remote "origin"]
	url = 

https://github.com/…….


	fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
	remote = origin
	merge = refs/heads/master
[gui]
	wmstate = normal
	geometry = 841x483+111+65 321 218
[http]
	postBuffer = 524288000

 

[go] solve the fatal error of go: concurrent map writes map non concurrent security

Map is not concurrency safe, when there are multiple concurrent growths reading and writing the same map  
A panic error occurs

concurrent map writes

For example, this error occurs in the following code:

var mMap map[int]int

func TestMyMap(t *testing.T) {
    mMap = make(map[int]int)

    for i := 0; i < 5000; i++ {
        go func() {
            mMap[i] = i
        }()
        go readMap(i)
    }
}
func readMap(i int) int {
    return mMap[i]
}

There are many ways to solve this problem. Now we use read-write lock,

Concurrent access to map is not safe, and undefined behavior will appear, leading to program exit. Therefore, if you want to access the map concurrently in multiple coroutines, you must provide some synchronization mechanism. Generally, you can control the concurrent access to the map by reading and writing the lock sync.rwmutex. Encapsulating the map and sync.rwmutex can realize the secure concurrent access to the map

Code after transformation

type SMap struct {
    sync.RWMutex
    Map map[int]int
}

func (l *SMap) readMap(key int) (int, bool) {
    l.RLock()
    value, ok := l.Map[key]
    l.RUnlock()
    return value, ok
}

func (l *SMap) writeMap(key int, value int) {
    l.Lock()
    l.Map[key] = value
    l.Unlock()
}

var mMap *SMap

func TestMyMap(t *testing.T) {
    mMap = &SMap{
        Map: make(map[int]int),
    }

    for i := 0; i < 5000; i++ {
        go func() {
            mMap.writeMap(i, i)
        }()
        go readMap(i)
    }
}
func readMap(i int) (int, bool) {
    return mMap.readMap(i)
}

  There are three ways:

1. Use channel
2. Use sync. Map
3. Use map but lock it