This article was created because Error: Cannot Not find Package appears every time a project is created or built

1. Preparation before creating a project

1.1 installedgolang.goland

1.2 check theGOPATH

echo $GOPATH

# If you need to change GOPATH, you can do the following (Mac)
vim ~/.bash_profile
export GOPATH=# Your target address
# save
:wq
# refresh
source ~/.bash_profile
Copy the code

1.3 in$GOAPTHCreate in folderpkg.bin ,srcThree folders

mkdir $GOPATH/pkg  # PKG stores the compiled package files
mkdir $GOPATH/src  # SRC holds the project source file. Our project directory is usually in this file
mkdir $GOPATH/bin  # bin stores compiled executable files
Copy the code

You can see that our directory structure looks like this

$GOAPTH | - bin | - PKG | - SRC | - (the project name, and then to create)Copy the code

1.4 Enabling the agent (Because downloading packages in China is slow or fails, configuring the agent can better help us obtain third-party packages)

Mac

vim ~/.bash_profile # to open the following

Copy the following code into bash_profile
export GO111MODUL=on  # Enable go Module
export GOPROXY=https://goproxy.io  # Set up domestic proxy

# save
:wq

# refresh
source ~/.bash_profile
Copy the code

Windows

set GO111MODUL=on  # Enable go Module
set GOPROXY=https://goproxy.io  This address is recommended for setting up a domestic proxy
Copy the code

1.5 Checking whether the configuration is successful

# input command
go env
Copy the code

1.6 Open Goland (do not create a project yet)

  • Configuration SettingsSetting -> Plugins... -> Go -> GOPATH

  • Uncheck theindex entire GOPATH(If checked, the current project will be regarded as GOPATH)
  • Golang will automatically be in$GOPATHsrcFind the project code in the directory
  • Check to see if the proxy is also configured in Goland

2. Create projects

2.1 Only need in$GOPATH/srcCan be created in directory

  • If an error occurs, it can be found in the projectTerminalThe configuration starts from 1.4

2.2 Initializing the Module in the project

go mod init project_name
Copy the code

2.3 Restart the project to refreshgo buildShow as available