How do you call a Go function in VSCode? - go

I have VSCode and the Go plugin installed. I am trying to call this function:
package main
import "fmt"
func printHello() {
fmt.Println("hello world")
}
First, I opened the VSCode Command Palette and chose Go: Test file, which threw a No tests found. Current file is not a test file. error.
Then I opened the VSCode Command Palette and chose Go: Test function at cursor - this threw the same error.
Then I created a sibling file with a _test.go naming convention:
package main
import (
"testing"
)
func TestHello(t *testing.T) {
msg, err := printHello()
}
This threw a build error: c:\path\to\my_test.go:8:18: main() used as value.
Then I added a simple return statement, which threw the following error:
go: cannot find main module, but found .git/config in c:\path\to\my_folder
to create a module there, run:
cd ..\.. && go mod init
I right-clicked the function name itself and chose the Go: Debug Test at Cursor function, and the Go: Generate unit tests for function option, which in-turn prompted me to install several other VSCode plugins, and prompted me to upgrade Go itself. The previous two Command Palette options started to fail with ENOENT errors, so I restarted VSCode, and got a new test function. I opened up the VSCode Debug Console but it wouldn't let me start a session there.
I right-clicked the parent folder and chose the Open in Integrated Terminal option, which started a WSL session - cd ..\.. && go mod init threw errors related to GOPATH:
me#COMPUTER:/mnt/c/path/to/my_folder$ go mod init
-bash: /c/go/bin/go.exe: No such file or directory
I tried determining what the WSL GOPATH was pointing to via Go: Show current GOPATH - it actually turned out that both the WSL and VSCode GOPATHs were incorrect.
I opened up a normal Command Prompt which had the correct GOPATH and I fired off go mod init which errored out (the previous guidance from VSCode was incorrect):
go: cannot determine module path for source directory C:\path\to\my_folder (outside GOPATH, module path must be specified)
Example usage:
'go mod init example.com/m' to initialize a v0 or v1 module
'go mod init example.com/m/v2' to initialize a v2 module
Run 'go help mod init' for more information.
I decided on a v2 Go module initialization (I don't know why one would opt for v0 or v1), which created a go.mod in the root directory of my project, but now I am seeing the following package-related errors:
gopls requires a module at the root of your workspace.
You can work with multiple modules by opening each one as a workspace folder.
Improvements to this workflow will be coming soon, and you can learn more here:
https://github.com/golang/tools/blob/master/gopls/doc/workspace.md.
How do I call a Go function in VSCode?

The answer turns out to be:
You need to create a *_test.go unit test harness and install more adjacent VSCode plugins.
You need to run go mod init blah somewhere outside of VSCode. blah is the name of your module. VSCode is unreliable with respect to the GOPATH.
There is a gotcha here where if you run go mod init main, this is valid but VSCode will throw misleading errors later on (see https://appliedgo.net/testmain/). You have to name it something else.
You need to re-open the VSCode workspace in a way such that go.mod is in the root of the workspace, or else VSCode runs into relative pathing errors.

Related

Universal scope and importing variables from one file to another

I am new at Golang. I am learning about universal scope and importing variables from one file to another.
Conditions:
System: Windows 11 x64
IDE: VS code
Language: GoLang
According to the universal scope I should be able to import variables from one file to another easily. Primary file: "main.go" and secondary file ""uniscope.go
Importing from uniscope.go into main.go
If the files are kept in the same folder directory then I can easily import using command: "go run main.go uniscope.go"
This runs without any error but until this command I get the error in main.go, "undeclared name", that is still not the main issue.
When I move the uniscope.go to another folder and then I run "go run main.go uniscope.go", it doesn't work, which is understandable as directory has been changed. So then I copy the path and paste it in import which in turns resolves the previous error, change the command to "go run main.go" but it throws out a new one.
"main.go:6:7: illegal character U+0073 's' in escape sequence"
I am not sure how I am wrong here. The video I am learning from is: https://www.youtube.com/watch?v=vYD9XWi_Xw8&list=PLve39GJ2D71xX0Ham0WoPaYfl8oTzZfN6&index=5
He is using itelliJ but I don't think that should be an issue.
I have tried the mentioned above and also tried finding the exact error on google. Just found a similar question posted on some Portuguese forum with no answers.
main.go:
package main
import "hello/world"
func main() {
println(world.Value)
}
world/world.go:
package world
const Value = 1
and run:
go mod init hello
go run .

Debugging go in vscode doesn't stop at breakpoints, says "Could not find file ..." when debugger starts

Ubuntu. vscode 1.62.1. go1.17.3. vscode go extension v0.29.0. delve v1.7.1.
I'm new to vscode and Go. I have many years of experience debugging Java apps in Eclipse.
I've constructed a small multi-module Go app. I can set a breakpoint in main and other functions in other modules. Inside main.go, I select "Start Debugging".
It starts the application, and I can tell it's working from the console, and that the REST endpoint responds with my dummy response.
However, it will NOT stop at breakpoints. As soon as I start the session, the red breakpoint markers suddenly become hollow, and hovering on one of them shows a message "Could not find file ...", which prints the full path to the source file in question.
When I start it, it shows the following in the console:
Starting: /home/.../go/bin/dlv-dap dap --check-go-version=false --listen=127.0.0.1:43347 --log-dest=3 from /home/.../...
DAP server listening at: 127.0.0.1:43347
I haven't modified the launch.json (I hope someday a friendlier interface to editing launch configurations is provided).
What else could I be doing wrong?
Update:
This is a screenshot showing main.go just before I press F5 (Start Debugging):
Notice that I have a breakpoint on the print statement, on the first line of main.
This is what I see after I press F5:
Notice that it printed "At start of main" in the console. It didn't stop at the breakpoint. Also notice message in tooltip when hovering over the breakpoint.
Update:
This is a view of my directory structure:
First, just make sure you have initiated your project with go mod init voltagems: that would explain the import "voltagems/xxx", but also helps delve to find your main.go file at debug time.
You should have go.mod and go.sum files beside main.go.
Second, check your go env output, making sure GOPATH and GOROOT are set to default paths.
The OP David M. Karr adds in the comments:
I did run "go mod init" when I first created the project, but I realized that I didn't like the root module name, so I changed it to "voltagems"
I believe you can edit directly go.mod first line, and make sure it says:
module voltagems
Then go mod verify + go mod tidy
Finally, go build .. Restart your VSCode (or the command Reload Window), and see if the issue persists.
The OP David M. Karr points out to a root cause:
There are symbolic links in my project path.
There is a "substitutePath" configuration in VSCode-Go that is used to map to absolute paths.
You can see this parameter mentioned in Debugging with Legacy Debug Adapter
substitutePath
Path mappings to apply to get from a path in the editor to a path in the compiled program (default: []).
That comes from issue 622 "debug: breakpoints don't work when working with symlink".
And commit 93f32bb
src/debugAdapter: add substitutePath config for debugging
This change adds a new configuration option to both launch and
attach requests.
substituePath takes an array that maps from string to string that is used to translate paths passed to the debugger and then
back to the client.
This allows users to translate their symlinked directories to the
files that were actually used to build the binary.
In addition this can also be used for remote debugging, and when the location of the files has moved since the program was built.
Example: you need a from and to key:
"substitutePath": [
{
"from": "/symlink/path/dir/on/local/machine",
"to": "/absolute/path/dir/on/local/machine",
},

RLock /storage/8D8B-150E/github.com/my-username/App/go.mod: function not implemented

I am having an issue while creating a new module in go with this command: go mod init <moduleName> it successfully created go.mod file but later then throws this error go: RLock /storage/mySdCard/github.com/my-username/App/go.mod: function not implemented & its not allowing me to install any go packages! Please help me to resolve this error or how can I fix it!!
I ran this command:
go mod init myApp
The output I got:
go: creating new go.mod: module myApp
go: updating go.mod: Lock /storage/8D8B-150E/Go/src/github.com/my-username/App/go.mod: function not implemented
The go command uses file-locking to ensure that the go.mod file is read in a consistent state if you run multiple go commands concurrently.
The RLock /storage/mySdCard/github.com/my-username/App/go.mod: function not implemented error that you're seeing indicates that the filesystem containing the go.mod file (/storage/mySdCard) does not support read-locking. (On most Unix-like operating systems, we use the flock system call.)
If you can't configure the filesystem to support locking and it isn't practical for you to work within a different filesystem that does, please file an issue at https://golang.org/issue/new, and mention issue #37461 (which is closely related) in the issue description.

missing go.sum entry for module providing package <package_name>

Using the buffalo framework,
after bootstraping it via buffalo new <project_name>
I am trying to run buffalo dev
Expecting to see:
project running on port 3000
But I am getting those error messages instead
actions/app.go:4:2: missing go.sum entry for module providing package github.com/gobuffalo/buffalo (imported by sc_api/actions); to add:go get sc_api/actions
actions/app.go:13:2: missing go.sum entry for module providing package github.com/gobuffalo/mw-csrf (imported by sc_api/actions); to add: go get sc_api/actions
actions/app.go has been generated by buffalo, but in case you are wondering the error does match the import statement in this file.
// app.go
package actions
import (
"github.com/gobuffalo/buffalo" // 1rst line
"github.com/gobuffalo/envy"
forcessl "github.com/gobuffalo/mw-forcessl"
paramlogger "github.com/gobuffalo/mw-paramlogger"
"github.com/unrolled/secure"
"sc_api/models"
"github.com/gobuffalo/buffalo-pop/v2/pop/popmw"
csrf "github.com/gobuffalo/mw-csrf" // 2nd line
i18n "github.com/gobuffalo/mw-i18n"
"github.com/gobuffalo/packr/v2"
)
What does it mean ? How do I fix it ?
It seems the issue has nothing to do with Buffalo and more with my lack of understanding of Go in general.
running go mod tidy solved the issue
This command goes through the go.mod file to resolve dependencies:
delete the packages that are not needed
download those needed
update the go.sum
I am still unsure which of those actions did the trick... but the project runs now.
ps: I'll let the in-depth explanation/correction to the Go wizard out here.
i got the same issue when building a docker image. i tried go mod tidy and
also go get -t . as suggested here https://github.com/golang/go/issues/44129. both didnt worked for me though but updating my docker builder to version 1.18 worked.
I use go mod tidy -e solved the problem. The -e flag (added in Go 1.16) causes go mod tidy to attempt to proceed despite errors encountered while loading packages.The more about mod tidy: https://go.dev/ref/mod#go-mod-tidy

goconvey Please run goconvey from within your $GOPATH cannot import absolute path

I'm setting up go and trying to get a simple project working with http://goconvey.co/
I have my $GOPATH set to /Users/joe/Desktop/playground/go
and when I run
$ go get github.com/smartystreets/goconvey
it downloads all good to my GOPATH
so when I create a project here
/Users/joe/Desktop/playground/go/some-project
and run goconvey I get
2015/02/04 14:41:05 shell.go:93: Please run goconvey from within your $GOPATH
My testing code is
package main
import (
. "github.com/smartystreets/goconvey/convey"
"testing"
)
func TestStuff(t *testing.T) {
Convey("Truth", t, func() {
Convey("is falsey", func() {
So(false, ShouldBeFalse)
})
})
}
I don't know why it connot find the files.
When I run go test it works perfectly.
Help?
All go code needs to be within $GOPATH/src/ for the GoConvey UI to work.
So, if your $GOPATH is set to
/Users/joe/Desktop/playground/go
then you will need to put your project at
/Users/joe/Desktop/playground/go/src/some-project
Your code is currently at
/Users/joe/Desktop/playground/go/some-project
Having said all that, the error message should probably be modified to read something like this:
Please run goconvey from within $GOPATH/src (also, symlinks might be problematic).
The name of the variable referenced by #VonC is probably a slight misnomer in this case.

Resources