How can I extract module versions from Go executables?

Mary-Kate Olsen
Release: 2024-10-31 08:57:30
Original
472 people have browsed it

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!