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?
Related
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"
}
]
}
When I launch in VSCode dlv dap debug, I get this message:
Couldn't start dlv dap:
Error:timed out while waiting for DAP server to start
I already have launch configurations for the project:
lunch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch file",
"type": "go",
"request": "launch",
"mode": "debug",
"program": "${workspaceFolder}",
"showLog": true,
"env": {
"GO111MODULE": "on"
}
}
]
}
and setting.json is :
{
"folders": [
{
"path": "."
}
],
"settings": {
"go.useCodeSnippetsOnFunctionSuggestWithoutType": true,
"go.autocompleteUnimportedPackages": true,
"go.gocodePackageLookupMode": "go",
"go.gotoSymbol.includeImports": true,
"go.useCodeSnippetsOnFunctionSuggest": true,
"explorer.confirmDelete": false,
"go.formatTool": "goimports",
"go.docsTool": "gogetdoc",
"go.buildFlags": [],
"explorer.confirmDragAndDrop": false,
"window.zoomLevel": 0.8,
"editor.minimap.enabled": false,
"go.useLanguageServer": true,
"go.delveConfig":{
"debugAdapter":"dlv-dap"
},
"[go]": {
"editor.snippetSuggestions": "none",
"editor.formatOnType": true,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},
"gopls": {
"experimentalWorkspaceModule": true,
"usePlaceholders": true, // add parameter placeholders when completing a function
"completionDocumentation": true // for documentation in completion items
}
},
}
The structure of the project is shown in the figure:
This might be happening due to recent updates to VS Code Go extension.
First options is to fix it by running "Go: Install/Update Tools" command from the Command Palette (Linux/Windows: Ctrl+Shift+P, Mac: ⇧+⌘+P).
Then, mark dlv & dlv-dap from the menu, and hit ok to start install/update.
Delve’s native DAP implementation is under active development, so take advantage of the most recent features and bug fixes by using Delve built from its master branch. The Go extension maintains this newest version of Delve separately from the officially released version of dlv and installs it with the name dlv-dap.
Second option, is to use legacy debug adapter. More on this in the link below ...
Check out the full documentation at https://github.com/golang/vscode-go/blob/master/docs/debugging.md
You might have some luck switching the delveConfig to use legacy mode:
"go.delveConfig":{
"debugAdapter":"legacy"
}
My team and I recently began seeing the same issue after updating VSCode. There's a little more info on this setting here: https://go.googlesource.com/vscode-go/+/HEAD/docs/debugging.md#switching-to-legacy-debug-adapter, but I believe root cause (if this does indeed solve your issue) is going to be your version of Golang is not the version targeted by dlv-dap. Anything below Go version 1.15 needs to use legacy mode, and the latest version of the delve debugger happens to skip legacy mode by default now.
I also needed to kill VSCode before this change took effect. According to the dlv-dap docs, you can also force it into legacy mode by switching launch.json's mode to "remote", so there's likely a few (maybe better) ways to resolve this issue.
For macOS users:
brew install delve
Linux/Windows: Ctrl+Shift+P, Mac: ⇧+⌘+P
It is my first time coding in Go. I am following an example and I succesfully can run the small applcation bellow. But I can't find a reason for not been ran in Visual Studio Code. So far I can see, I follow the suggestion found in this answer saying: "... Since your package is outside of $GOPATH, you may need to create a module file. You'll need to init your go module using".
go.mod
module jimis.net/snippetbox
go 1.15
main.go
package main
import (
"log"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", home)
mux.HandleFunc("/snippet", showSnippet)
mux.HandleFunc("/snippet/create", createSnippet)
log.Println("Starting server on :4000")
err := http.ListenAndServe(":4000", mux)
log.Fatal(err)
}
handlers.go
package main
import (
"fmt"
"net/http"
"strconv"
)
func home(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Write([]byte("Hello from Snippetbox"))
}
func showSnippet(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.URL.Query().Get("id"))
if err != nil || id < 1 {
http.NotFound(w, r)
return
}
fmt.Fprintf(w, "Display a specific snippet with ID %d...", id)
}
func createSnippet(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
http.Error(w, "Method Not Allowed", 405)
return
}
w.Write([]byte("Create a new snippet..."))
}
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": []
}
]
}
output
Starting linting the current package at c:\WSs\snippetbox\cmd\web
Starting "go vet" under the folder c:\WSs\snippetbox\cmd\web
Starting building the current package at c:\WSs\snippetbox\cmd\web
Not able to determine import path of current package by using cwd: c:\WSs\snippetbox\cmd\web and Go workspace:
C:\WSs\snippetbox\cmd\web>Finished running tool: C:\Go\bin\go.exe vet .
C:\WSs\snippetbox\cmd\web>Finished running tool: C:\Go\bin\go.exe build -i -o C:\Users\DEMETR~1.EXT\AppData\Local\Temp\vscode-go7pNgfo\go-code-check .
Project structure (pkg and ui folder are emptys)
VS Code settings.json
{
"workbench.startupEditor": "newUntitledFile",
"editor.minimap.enabled": false,
"go.formatTool": "goimports",
"explorer.confirmDelete": false,
"go.toolsEnvVars": {
"GO111MODULE": "on" /// *** I tried both on and off with no changes on my issue
}
}
go env
PS C:\WSs\snippetbox> go env
set GO111MODULE=
set GOARCH=amd64
set GOBIN=
set GOCACHE=C:\Users\aa.bb.ext\AppData\Local\go-build
set GOENV=C:\Users\aa.bb.ext\AppData\Roaming\go\env
set GOEXE=.exe
set GOFLAGS=
set GOHOSTARCH=amd64
set GOHOSTOS=windows
set GOINSECURE=
set GOMODCACHE=C:\Users\aa.bb.ext\go\pkg\mod
set GONOPROXY=
set GONOSUMDB=
set GOOS=windows
set GOPATH=C:\Users\aa.bb.ext\go
set GOPRIVATE=
set GOPROXY=https://proxy.golang.org,direct
set GOROOT=c:\go
set GOSUMDB=sum.golang.org
set GOTMPDIR=
set GOTOOLDIR=c:\go\pkg\tool\windows_amd64
set GCCGO=gccgo
set AR=ar
set CC=gcc
set CXX=g++
set CGO_ENABLED=1
set GOMOD=C:\WSs\snippetbox\go.mod
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\DEMETR~1.EXT\AppData\Local\Temp\go-build201665690=/tmp/go-build -gno-record-gcc-switches
PS C:\WSs\snippetbox>
In case it is relevant, I added this extension to VSCode
Rich Co Language Support for Visual Studio Code v0.16.1
But all goes fine from command line
PS C:\WSs\snippetbox> go run ./cmd/web
2020/08/20 18:19:51 Starting server on :4000
Thanks to discussion in Go Slack (GOPHERS), someone guided me to this solution. Hopefully it can help future readers.
1 - add program and cwd as bellow to launch
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch",
"type": "go",
"request": "launch",
"mode": "auto",
"env": {},
"args": [],
"program": "${workspaceRoot}/cmd/web",
"cwd": "${workspaceFolder}"
}
]
}
2 - code must be outside GOPATH floder
3 - add go.useLanguageServer": true (C:\Users..\AppData\Roaming\Code\User\settings.json)
{
"workbench.startupEditor": "newUntitledFile",
"editor.minimap.enabled": false,
"go.formatTool": "goimports",
"explorer.confirmDelete": false,
"go.useLanguageServer": true,
"go.toolsEnvVars": {
"GO111MODULE": "on"
}
}
4 - here are my current GO extensions although I don't know how relevant each one is for my solution
PS C:\> code --list-extensions
...
casualjim.gotemplate
dunstontc.vscode-go-syntax
golang.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.
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.