如何正确获取go build的返回码?

I want to add go build into a precommit hook so that not to ship unbuildable code.

If the build succeeds, I want to continue commit, otherwise fail and reject commit.

How do I do it properly?

Any pre-commit hook will be executed by a git bash (even on Windows), so you can script it through a regular bash script.

See Git Hooks

Exiting non-zero from this hook aborts the commit, although you can bypass it with git commit --no-verify.

#!/bin/bash
set -e
go build

(from "Checking Bash exit status of several commands efficiently")
That way, you can chain multiple commands (like go vet, other go linters). If any of them fail, the pre-commit hook will prevent the commit.