Debug file other than main.go in VS Code - go

I am writing a CLI in go using VS code editor. I am not able to figure out how to debug a code section.
My directory structure is :
- test
- main.go
- cmd
- login.go
- root.go
I have set breakpoints in login.go but if I run "Start Debugging" in this file, I get error
Can not debug non-main package
Process exiting with code: 1
I tried running debugger in main.go but the debugger won't go to login.go file as I we have not explicitly written test login
API server listening at: 127.0.0.1:48423
A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
cd .
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.
Usage:
test [command]
Available Commands:
help Help about any command
login A brief description of your command
Flags:
--config string config file (default is $HOME/.test.yaml)
-h, --help help for test
-t, --toggle Help message for toggle
Use "test [command] --help" for more information about a command.
main.go file
package main
import "test/cmd"
func main() {
cmd.Execute()
}
login.go file
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
// loginCmd represents the login command
var loginCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("login called")
name, _ := cmd.Flags().GetString("username")
pwd, _ := cmd.Flags().GetString("password")
userInfo := name + ":" + pwd
},
}
func init() {
rootCmd.AddCommand(loginCmd)
// Here you will define your flags and configuration settings.
loginCmd.Flags().StringP("username", "u", "", "Specifies the user")
loginCmd.Flags().StringP("password", "p", "", "Specifies the password for the user")
loginCmd.Flags().StringP("manager", "m", "", "Specifies the environement where user wants to login")
}
settings.json
{
"go.gopath":"/Users/deepakpatankar/go"
}
launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${fileDirname}",
"env": {},
"args": []
}
]
}
Please guide me how I can see the variable values in debug mode like for variable name. Though using Println is fine, but this source code is part of a bigger project, so I want to see how I can use the debugger ?

Modify your launch.json as below:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceRoot}",
"env": {},
"args": [],
"port": 8080,
"host": "127.0.0.1"
}
]
}
You'll learn that some differences are there from yours.
...
"mode": "debug",
"program": "${workspaceRoot}",
...

You can add flags to the "args": [] array in your vscode settings like this:
"args": ["login", "-u", "username", "-p", "password"]
This will make sure when you run debug you end up in the login command with the given flags.

Related

Compile two golang files into one executable and run in vscode

I have a go program with a main.go and a sub.go. When I run it under the debugger, main cannot see the function defined in sub. I tried creating a tasks.json but when I run it nothing happens.]
The MS documentaiton linked is for Node Package Manager and it doesn't state where the identifier for the task is placed in the configuration file
Here is my tasks.json:
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "echo",
"type": "shell",
"command": "go run crypto.go sbox.go state.go utility.go"
}
]
}

Fail to use the Go Delve debugger with VSCode

This is my first day with the Go language and I wanted to debug a simple REST API.
package main
import (
"fmt"
"log"
"net/http"
)
func homePage(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Homepage EndPoint Hit")
}
func handleRequests() {
http.HandleFunc("/", homePage)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func main() {
handleRequests()
}
Here is my debug configuration
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Launch file",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceRoot}"
}
]
}
The settings.json is
{
"redhat.telemetry.enabled": true,
"vs-kubernetes": {
"vscode-kubernetes.helm-path.mac": "/Users/gsinha/.vs-kubernetes/tools/helm/darwin-amd64/helm"
},
"go.toolsManagement.autoUpdate": true,
"files.autoSave": "afterDelay",
"code-runner.clearPreviousOutput": true,
"code-runner.runInTerminal": true,
"code-runner.saveAllFilesBeforeRun": true
}
When I try to start a debug session using F5, I get this error.
Starting: /Users/gsinha/go/bin/dlv-dap dap --listen=127.0.0.1:54320 --log-dest=3
DAP server listening at: 127.0.0.1:54320
Build Error: go build -o /Users/gsinha/go/src/rest/__debug_bin -gcflags all=-N -l /Users/gsinha/go/src/rest
go tool: no such tool "compile"
go tool: no such tool "compile"
go tool: no such tool "compile"
go tool: no such tool "compile" (exit status 2)
I am able to run the application but when I try to start a debug session it fails unexpectedly.
Check your go env, the compile file should be in path GOTOOLDIR.
If not, check your go installation.
Maybe helpful: All of a sudden go tool: no such tool "compile"
--- update ---
It should be a go env problem.
Could u check go env and go build using the vscode internal terminal?
Have u ever chose go sdk version in vscode?

How can I debug specific functions?

I have a website that has several different functions . I can get to my website by using localhost:5000/ , when I run it in debug mode using vscode-go debugger I get the following message
API server listening at: 127.0.0.1:52238
I have a Name function that returns several strings but I can not hit the breakpoint in debug mode . I put a breakpoint in my Name function and put the url as follows: 127.0.0.1:52238/name however it does not hit the breakpoint. What could be going on here ? My code is below if i run the application normally and put http://localhost:5000/name then everything works but in debug mode this 127.0.0.1:52238/name does not hit the breakpoint or page . I am using Go as a backend api so I'll need to hit url endpoints to see what's going on. Is there someway that I can make the debug port also :5000 ?
-- Main
package main
import (
"github.com/gorilla/mux"
"runtime"
"./Models"
"./Controllers"
)
func main() {
Controllers.CircleRoutes(r)
srv := &http.Server{
ReadTimeout: 20 * time.Second,
WriteTimeout: 20 * time.Second,
IdleTimeout: 120 * time.Second,
Addr: ":5000",
}
srv.ListenAndServe()
}
// Circles Route
package Controllers
func Name(w http.ResponseWriter, r *http.Request) {
var result string
r.ParseForm()
result = "Success"
io.WriteString(w, result)
}
func CircleRoutes(r *mux.Router) {
r.HandleFunc("/name", Name)
}
It looks you are using vscode-go debugger.
You can configure the port from launch.json configuration file from your vscode.
The config should look like this:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "debug",
"remotePath": "",
"port": 2345,
"host": "127.0.0.1",
"program": "${workspaceRoot}",
"env": {
"GOPATH": <your GOPATH>
},
"args": [],
"showLog": true
}
],
"go.lintTool": "gometalinter"
}
You can change port from above settings. To find launch.json, just ctrl+P and type launch.json it will show dropdown result of search in your vscode.

Visual Studio Code Task Argument

I'm trying to create some tasks in Visual Studio Code to run all the tests in my go project.
I usually execute the tests on the command line using:
go test ./...
In Visual Studio Code my tasks.json looks like this:
{
"version": "0.1.0",
"command": "go",
"tasks": [
{
"taskName": "build",
"isBuildCommand": true
},
{
"taskName": "test",
"isTestCommand": true,
"args": ["./..."]
}
]
}
So Build works fine (CTRL + SHIFT + B)
But when I try to run the tests (CTRL + SHIFT + T) the following error occurs:
go: unknown subcommand "./..."
It seems to be omitting the "test" param, but when I comment out the args it runs go test fine.
Any ideas?
THIS MAY BE A BUG
VSCode Reverse Args and Task as of v0.8.0
This may be a bug that still persists in the newer versions. As of v0.9.1 I have not had a chance to test. Prior to 0.9.1 at least one hack worked by reversing the task and it's arg as in the following example:
{
"version": "0.1.0",
"command": "go",
"tasks": [
{
"taskName": "build",
"isBuildCommand": true
},
{
"taskName": "./...",
"isTestCommand": true,
"args": ["test"]
}
]
}
It's hard to believe that this has still persisted until v0.8.0 so there may be a preferred solution that I have not discovered.
Here is a link to a prior post that deals with a similar issue:
Define multiple tasks in VSCode
Scroll down to my answer for more explanation.

Debug Electron using Visual Studio Code on Mac

Refer to this stackoverflow question:
I am trying to do the same but on Mac. I have the same as above,except instead of
"runtimeExecutable": "node_modules/electron-prebuilt/dist/electron.exe"
I have it as
"runtimeExecutable": "/usr/local/bin/electron"
Since F5 on mac is mapped to screen dimmer, I launched the app from command line as follows:
electron --debug-brk=5858 .
My program launched and ran without breaking.
So I modified keybindings.json like so:
[
{ "key": "shift+ctrl+f5", "command": "workbench.action.debug.play",
"when": "inDebugMode" },
{ "key": "shift+ctrl+f5", "command": "workbench.action.debug.start",
"when": "!inDebugMode" },
]
I tried launching the program by pressing shift+ctrl+f5 - I am still unable to debug my program.
I get the following error:
Error: Connection Failed
when I run node instead of electron, the debugger works fine when the the app is launched from command line
PLEASE HELP!
Thanks in advance
This is your launch.json. The important parts are runtimeExecutable and env. For VS Code 0.8.0, debugging only mostly works using electron 0.30.6.
{
"version": "0.1.0",
// List of configurations. Add new configurations or edit existing ones.
// ONLY "node" and "mono" are supported, change "type" to switch.
"configurations": [
{
// Name of configuration; appears in the launch configuration drop down menu.
"name": "Launch electron",
// Type of configuration. Possible values: "node", "mono".
"type": "node",
// Workspace relative or absolute path to the program.
"program": "main.js",
// Automatically stop program after launch.
"stopOnEntry": false,
// Command line arguments passed to the program.
"args": [],
// Workspace relative or absolute path to the working directory of the program being debugged. Default is the current workspace.
"cwd": ".",
// Workspace relative or absolute path to the runtime executable to be used. Default is the runtime executable on the PATH.
"runtimeExecutable": "node_modules/electron-prebuilt/dist/electron.app/Contents/MacOS/electron",
// Optional arguments passed to the runtime executable.
"runtimeArgs": [],
// Environment variables passed to the program.
"env": {"ATOM_SHELL_INTERNAL_RUN_AS_NODE": "0"},
// Use JavaScript source maps (if they exist).
"sourceMaps": false,
// If JavaScript source maps are enabled, the generated code is expected in this directory.
"outDir": null
},
{
"name": "Attach",
"type": "node",
// TCP/IP address. Default is "localhost".
"address": "localhost",
// Port to attach to.
"port": 5858,
"sourceMaps": false
}
]
}
Install 0.30.6 of electron-prebuilt in your project directory using npm install –-save-dev electron-prebuilt#0.30.6

Resources