いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-135 (embedパッケージを使ってバージョン情報などを埋め込み)

概要

前回、ビルド時に -ldflags を使ってパッケージ情報を埋め込むサンプルを記載しました。

devlights.hatenablog.com

Go 1.16 から embed パッケージが追加されたので、今後はこれ使ったほうが楽かもって思いました。

golang.org

ついでにサンプル作ったので、以下にメモメモ。

サンプル

それぞれ別々のファイルにしておいて埋め込む

/*
   Go 1.16 から追加された embed パッケージを利用して内部の変数に外部ファイルデータを埋め込むサンプルです.

   Commands:
       $ git describe --tags --abbrev=0 > version.txt
       $ git rev-list -1 HEAD > revision.txt
       $ git describe --tags > build.txt
       $ go run .
*/
package main

import (
    _ "embed"
    "fmt"
    "os"
)

// Version and Revision
//
// Commands:
//   $ git describe --tags --abbrev=0 > version.txt
//   $ git rev-list -1 HEAD > revision.txt
//   $ git describe --tags > build.txt
var (
    //go:embed version.txt
    version string
    //go:embed revision.txt
    revision string
    //go:embed build.txt
    build string
)

func main() {
    os.Exit(run())
}

func run() int {
    fmt.Printf("Version : %s\n", version)
    fmt.Printf("Revision: %s\n", revision)
    fmt.Printf("Build   : %s\n", build)

    return 0
}

実行すると以下のようになります。

default: run

prepare:
   @git describe --tags --abbrev=0 > version.txt
   @git rev-list -1 HEAD > revision.txt
   @git describe --tags > build.txt

run: prepare
   @go run -race .
gitpod /workspace/try-golang $ (cd ./cmd/version_and_revision/with_embed; make)
Version : v0.2.3
Revision: 22c87c3668ec147d3d412afc1e7b6466611dbdde
Build   : v0.2.3-79-g22c87c3

一つのファイルにバージョンとかをまとめておいて埋め込む

/*
   Go 1.16 から追加された embed パッケージを利用して内部の変数に外部ファイルデータを埋め込むサンプルです.

   Commands:
       $ git describe --tags --abbrev=0 > version.txt
       $ git rev-list -1 HEAD >> version.txt
       $ git describe --tags >> version.txt
       $ go run -race .
*/
package main

import (
    "bytes"
    _ "embed"
    "fmt"
    "os"
)

type version []byte

func (v version) String() string {
    buf := bytes.NewBuffer(v)
    get := func() string { v, _ := buf.ReadString('\n'); return v }

    return fmt.Sprintf("Version : %sRevision: %sBuild   : %s", get(), get(), get())
}

//go:embed version.txt
var v []byte

func main() {
    os.Exit(run())
}

func run() int {
    fmt.Print(version(v))
    return 0
}

実行すると以下のようになります。

default: run

prepare:
   @git describe --tags --abbrev=0 > version.txt
   @git rev-list -1 HEAD >> version.txt
   @git describe --tags >> version.txt

run: prepare
   @go run -race .
gitpod /workspace/try-golang $ (cd ./cmd/version_and_revision/with_embed2; make)
Version : v0.2.3
Revision: eee95c82887f9606663eed84643cec6d6cd0b4c6
Build   : v0.2.3-80-geee95c8

過去の記事については、以下のページからご参照下さい。

  • いろいろ備忘録日記まとめ

devlights.github.io

サンプルコードは、以下の場所で公開しています。

  • いろいろ備忘録日記サンプルソース置き場

github.com

github.com

github.com