首頁 > 軟體

Golang專案在github建立release後自動生成二進位制檔案的方法

2023-03-19 06:03:17

希望達到的效果

工具類的Golang專案需要編譯成二進位制檔案後在命令列中執行,所以希望在github裡面建立一個新的release後能自動編譯成針對各個平臺的二進位制檔案,如下圖所示:

實現方式

藉助 GoReleaser 這款工具配合 github actions 可以很方便實現這種效果,下面講解下具體實現方法。

首先需要在 Golang 專案的根目錄建立 GoReleaser 組態檔 .goreleaser.yaml,內容如下:

# This is an example .goreleaser.yml file with some sensible defaults.
# Make sure to check the documentation at https://goreleaser.com
before:
  hooks:
    # You may remove this if you don't use go modules.
    - go mod tidy
    # you may remove this if you don't need go generate
    - go generate ./...
builds:
  - env:
      - CGO_ENABLED=0
    goos:
      - linux
      - windows
      - darwin
 
archives:
  - format: tar.gz
    # this name template makes the OS and Arch compatible with the results of uname.
    name_template: >-
      {{ .ProjectName }}_
      {{- title .Os }}_
      {{- if eq .Arch "amd64" }}x86_64
      {{- else if eq .Arch "386" }}i386
      {{- else }}{{ .Arch }}{{ end }}
      {{- if .Arm }}v{{ .Arm }}{{ end }}
    # use zip for windows archives
    format_overrides:
    - goos: windows
      format: zip
checksum:
  name_template: 'checksums.txt'
snapshot:
  name_template: "{{ incpatch .Version }}-next"
changelog:
  sort: asc
  filters:
    exclude:
      - '^docs:'
      - '^test:'
 
# The lines beneath this are called `modelines`. See `:help modeline`
# Feel free to remove those if you don't want/use them.
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj

然後建立 github actions 組態檔, 在Golang專案的根目錄建立 .github 資料夾,在這個資料夾裡面建立 workflows 資料夾,在 workflows 資料夾裡面建立 release.yaml 檔案,內容如下:

name: goreleaser
 
on:
  push:
    # run only against tags
    tags:
      - '*'
 
permissions:
  contents: write
  # packages: write
  # issues: write
 
jobs:
  goreleaser:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
      - run: git fetch --force --tags
      - uses: actions/setup-go@v3
        with:
          go-version: '>=1.20.2'
          cache: true
      # More assembly might be required: Docker logins, GPG, etc. It all depends
      # on your needs.
      - uses: goreleaser/goreleaser-action@v4
        with:
          # either 'goreleaser' (default) or 'goreleaser-pro':
          distribution: goreleaser
          version: latest
          args: release --clean
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          # Your GoReleaser Pro key, if you are using the 'goreleaser-pro'
          # distribution:
          # GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}

這個檔案的內容不需要做任何修改,提交程式碼並將程式碼 push 到 github 後,在 github 的 release 頁面新建一個 release 後,在 Actions 頁面就可以看到有一個workflow在執行:

等這個 workflow 執行完成以後,在 release 的 Assets 裡面就會出現針對各個平臺的二進位制檔案。

到此這篇關於Golang專案在github建立release後如何自動生成二進位制檔案的文章就介紹到這了,更多相關go自動生成二進位制檔案內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com