Home >Backend Development >Golang >How can I extract module versions from Go executables?

How can I extract module versions from Go executables?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-31 08:57:30618browse

How can I extract module versions from Go executables?

Extracting Module Versions from Go Executables

In Go binary executables, the Go tool embeds module and dependency information. This information can be accessed using the runtime/debug.ReadBuildInfo() function.

Problem

You need to display the versions of the modules used in your Go executables, but you're struggling with the implementation. You've considered using ldflags, but it's not scalable.

Solution

The debug.ReadBuildInfo() returns a list of debug.Module instances, which provide the following information:

  • Path: The module's path
  • Version: The module's version
  • Sum: The module's checksum
  • Replace: The module it replaces

Code Example

The following code demonstrates how to use ReadBuildInfo() to retrieve module versions:

<code class="go">package main

import (
    "fmt"
    "runtime/debug"
)

func main() {
    bi, ok := debug.ReadBuildInfo()
    if !ok {
        // Handle failure
    }

    for _, dep := range bi.Deps {
        fmt.Printf("Dependency: %s, Version: %s\n", dep.Path, dep.Version)
    }
}</code>

This example will output the paths and versions of all dependencies used by the executable.

The above is the detailed content of How can I extract module versions from Go executables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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