"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Retrieve Module Versions from Code in Go?

How Can I Retrieve Module Versions from Code in Go?

Published on 2024-11-09
Browse:535

How Can I Retrieve Module Versions from Code in Go?

Retrieving Module Versions from Code in Go

In Go, the runtime/debug package provides access to detailed information about a program's dependencies and modules. This functionality enables you to retrieve and display module versions from within the code.

The debug.ReadBuildInfo() function returns a BuildInfo structure that contains a list of all imported dependencies. Each module or dependency is represented by a Module struct, which includes the following fields:

  • Path: The module's import path.
  • Version: The module's version.
  • Sum: The checksum of the module's code.
  • Replace: The module that replaces this one, if any.

To retrieve and display the module versions, you can use code like this:

package main

import (
    "fmt"
    "log"
    "runtime/debug"
)

func main() {
    bi, ok := debug.ReadBuildInfo()
    if !ok {
        log.Printf("Failed to read build info")
        return
    }

    for _, dep := range bi.Deps {
        fmt.Printf("Module: %s, Version: %s\n", dep.Path, dep.Version)
    }
}

This example will load the module and dependency information into a BuildInfo structure and iterate over the dependencies, printing out their paths and versions. You can modify this code to display the information in your desired format, such as the example in the question.

This approach avoids the need for using ldflags to set the versions externally. Instead, it relies on information provided by Go itself, making it a reliable and scalable solution for managing module versions.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3