Skip to content

Instantly share code, notes, and snippets.

@KEINOS
Created September 27, 2021 03:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KEINOS/9cbad9941ad797b8d75123e40f7fd4c8 to your computer and use it in GitHub Desktop.
Save KEINOS/9cbad9941ad797b8d75123e40f7fd4c8 to your computer and use it in GitHub Desktop.
[Golang] How to get imported module/package version from main.go

[Golang] How to get the version of imported non-standard module from main

tl; dr

Use debug.ReadBuildInfo() of "runtime/debug" module.

ts; dr

This is an example to get the version of "golang.org/x/xerrors" package from the main source code.

package main

import (
	"fmt"

	"log"

	"golang.org/x/xerrors"
	"runtime/debug"
)

func main() {
	buildInfo, ok := debug.ReadBuildInfo()
	if !ok {
		err := xerrors.New("failed to get build info")

		log.Fatal(err)
	}

	for _, modDep := range buildInfo.Deps {
		fmt.Println("module name:", modDep.Path)
		fmt.Println("module version:", modDep.Version)
	}
}
// Output:
// module name: golang.org/x/xerrors
// module version: v0.0.0-20200804184101-5ec99f83aff1

View it online: Go Playground

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment