Tag Archives: Go

GoLand import the local package Error [How to Solve]

The local package imported by GoLand is red, recording a very speechless problem

Shortly after contacting go, I found a problem when I wrote a little demo with a blog. Importing another local package in one package will be popular, and importing a third-party package is no problem

Solution: open this setting of goland

[Solved] Installing github.com/uudashr/gopkgs/v2/cmd/[email protected] FAILED和cannot install, GOBIN must be an ab

When configuring the go environment with vscode

Installing github.com/uudashr/gopkgs/v2/cmd/[email protected] FAILED
"stderr": "cannot install, GOBIN must be an absolute path\n" // Prompt to set absolute path

Go components can be installed here, but go.exe installation in Bin cannot be found

We enter go env to view the environment configuration

set GO111MODULE=on
set GOARCH=amd64
set GOBIN=D:\Program Files\Go\bin  // Here is the path used to install the go component
set GOCACHE=C:\Users\44305\AppData\Local\go-build
set GOENV=C:\Users\44305\AppData\Roaming\go\env  // --------------------------------这里是env文件存放的位置
set GOEXE=.exe
set GOEXPERIMENT=
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:\Users\44305\go\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:\Users\44305\go
set GOPRIVATE=
set GOPROXY=https://goproxy.io,direct
set GOROOT=D:\Program Files\Go // ---------------Here is the location of the go installation
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=D:\Program Files\Go\pkg\tool\windows_amd64
set GOVCS=
set GOVERSION=go1.17.1
set GCCGO=gccgo
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=NUL
set CGO_CFLAGS=-g -O2
set CGO_CPPFLAGS=
set CGO_CXXFLAGS=-g -O2
set CGO_FFLAGS=-g -O2
set CGO_LDFLAGS=-g -O2
set PKG_CONFIG=pkg-config
set GOGCCFLAGS=-m64 -mthreads -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=C:\Users\44305\AppData\Local\Temp\go-build352704544=/tmp/go-build -gno-record-gcc-switches

Use the command line to find that the settings still do not work. Finally, modify the file directly
1) the first step is to find the env file
set goenv = C:\users\44305\appdata\roaming\go\env// ——————————————- here is the location where the env file is stored

2) The second step is to open it with a notebook

3) the third step is to set the path here to the bin file in the following directory
set goroot = D:\program files\go// ——————– here is the location where go is installed

Finally, close vscode and then open it to install successfully

Tools environment: GOPATH=C:\Users\44305\go, GOBIN=D:\Program Files\Go\bin
Installing 8 tools at the configured GOBIN: D:\Program Files\Go\bin in module mode.
  go-outline
  gotests
  gomodifytags
  impl
  goplay
  dlv
  staticcheck
  gopls

Installing github.com/ramya-rao-a/[email protected] (D:\Program Files\Go\bin\go-outline.exe) SUCCEEDED
Installing github.com/cweill/gotests/[email protected] (D:\Program Files\Go\bin\gotests.exe) SUCCEEDED
Installing github.com/fatih/[email protected] (D:\Program Files\Go\bin\gomodifytags.exe) SUCCEEDED
Installing github.com/josharian/[email protected] (D:\Program Files\Go\bin\impl.exe) SUCCEEDED
Installing github.com/haya14busa/goplay/cmd/[email protected] (D:\Program Files\Go\bin\goplay.exe) SUCCEEDED
Installing github.com/go-delve/delve/cmd/[email protected]st (D:\Program Files\Go\bin\dlv.exe) SUCCEEDED
Installing honnef.co/go/tools/cmd/[email protected] (D:\Program Files\Go\bin\staticcheck.exe) SUCCEEDED
Installing golang.org/x/tools/[email protected] (D:\Program Files\Go\bin\gopls.exe) SUCCEEDED

All tools successfully installed. You are ready to Go. :)

[Solved] Error: SRC refspec master doors not match any

Unable to submit successfully when pushing

error: src refspec master does not match any 
error: failed to push some refs to 'https://gitee.com/xxxxxxx/cool-admin-midway.git'

The content of the question is:

Error: SRC refspec master does not match any
error: failed to push some references to ” https://gitee.com/xxxxxxx/cool-admin-midway.git ’

That is, the warehouse is empty
solution:

Use the git add XXX. Py ( git add. add all) instruction to add all files, and then perform git commit – M “init” to commit all files,

git commit -m "init"

Then in execution

$ git remote add origin xxxxxxxx.git

Last use

$ git push -u origin master

In this way, the code can be uploaded successfully. You can see that the code is uploaded successfully in the warehouse

Summary:

In fact, you only need to do the following steps to upload local projects to GitHub

 1. create a local repository (i.e. folder) and turn it into a Git repository by git init.

 2. Copy the project into this folder and add it to the repository via git add . Add the project to the repository.

 3. commit the project to the repository by using git commit -m "comment content".

 4, after setting up the SSH key on Github, create a new remote repository by git remote add origin https://github.com/guyibang/TEST2.git Associate a local repository with a remote repository.

 5. Finally, push the project from the local repository to the remote repository (i.e. Github) via git push -u origin master; (if the README file is automatically created when you create a new remote repository, it will report an error, see above for the solution).

Complete steps for uploading files locally to gitee

Git global settings:

git config --global user.name "namexxxx"
git config --global user.email "emailxxx"

Create a git repository:

mkdir test_code
cd test_code
git init
git add xxxx (to add files, git add . Add all)
git commit -m "first commit"
git remote add origin https://xxxxx.git
git push -u origin master

[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(),
		)),
	)