Home >Backend Development >Golang >How Can I Retrieve Module Versions from Within Go Code?

How Can I Retrieve Module Versions from Within Go Code?

Susan Sarandon
Susan SarandonOriginal
2024-11-03 09:03:29898browse

How Can I Retrieve Module Versions from Within Go Code?

Retrieving Module Versions from Within Go Code

The Go tooling includes module and dependency information within the compiled binary. Harnessing this feature, the runtime/debug.ReadBuildInfo() function presents a method to access this data while your application is executing. It furnishes an array containing dependency details, inclusive of module path and release number.

For each module or dependency, this array contains a debug.Module structure, detailed below:

type Module struct {
    Path    string  // module path
    Version string  // module version
    Sum     string  // checksum
    Replace *Module // replaced by this module
}

To exemplify this process:

package main

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

    "github.com/icza/bitio"
)

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

    for _, dep := range bi.Deps {
        fmt.Printf("Dep: %+v\n", dep)
    }
}

When executed on the Go Playground, it yields the following output:

Dep: &{Path:github.com/icza/bitio Version:v1.0.0 Sum:h1:squ/m1SHyFeCA6+6Gyol1AxV9nmPPlJFT8c2vKdj3U8= Replace:<nil>}

Refer to the related question for further insights: How to acquire detailed Go build logs, along with all packages utilized in GOPATH and "go module" modes?

The above is the detailed content of How Can I Retrieve Module Versions from Within Go Code?. 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