Home > Backend Development > Golang > Can Go Detect GoLand Debugger Attachment Like C#\'s `Debugger.IsAttached`?

Can Go Detect GoLand Debugger Attachment Like C#\'s `Debugger.IsAttached`?

Susan Sarandon
Release: 2024-12-06 05:22:09
Original
897 people have browsed it

Can Go Detect GoLand Debugger Attachment Like C#'s `Debugger.IsAttached`?

Detecting GoLand Debugger Execution within a Program

In C#, a running program can identify whether it's under debugger supervision through the "System.Diagnostics.Debugger.IsAttached" method.

Can Go achieve a similar functionality? This is particularly desirable for disabling timeouts while code is being debugged.

Specifically, this question arises in the context of using the GoLand debugger.

Solution

Using Build Tags:

  1. Create two Go source files: "isdelve/delve.go" and "isdelve/nodelve.go."
  2. In "isdelve/delve.go," add the following build tag:

    // +build delve
    Copy after login
  3. In "isdelve/nodelve.go," add the following build tag:

    // +build !delve
    Copy after login
  4. Add a "package isdelve" declaration to both files and declare the "Enabled" constant:

    package isdelve
    
    const Enabled = true
    
    // or
    
    package isdelve
    
    const Enabled = false
    Copy after login
  5. Create a third Go file, "a.go," which imports the "isdelve" package:

    package main
    
    import (
        "isdelve"
        "fmt"
    )
    
    func main() {
        fmt.Println("delve", isdelve.Enabled)
    }
    Copy after login

Configuring GoLand:

  1. Open the "Run/Debug Configurations" window in GoLand.
  2. Add "-tags=delve" to the "Go tool arguments" section.

Usage:

  • When running "go run a.go" outside of GoLand, the program will report "delve false."
  • When using dlv to debug, use "dlv debug --build-flags='-tags=delve' a.go." This will report "delve true."

Alternative:

Alternatively, delve's "set" command can manually set a variable after starting the debugger.

The above is the detailed content of Can Go Detect GoLand Debugger Attachment Like C#\'s `Debugger.IsAttached`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template