open /bin/migrate: operation not permitted when building Go tags

Issue

I’m following this Go + GraphQL tutorial https://www.howtographql.com/graphql-go/4-database/ and I got stuck at the point where I’m trying to install and then run migrations.

The entire command chain is

go get -u github.com/go-sql-driver/mysql
go build -tags 'mysql' -ldflags="-X main.Version=1.0.0" -o $GOPATH/bin/migrate github.com/golang-migrate/migrate/v4/cmd/migrate/
cd internal/pkg/db/migrations/
migrate create -ext sql -dir mysql -seq create_users_table
migrate create -ext sql -dir mysql -seq create_links_table

But specifically in

go build -tags 'mysql' -ldflags="-X main.Version=1.0.0" -o $GOPATH/bin/migrate github.com/golang-migrate/migrate/v4/cmd/migrate/
cd internal/pkg/db/migrations/

I will get the following error in my terminal:

go build github.com/golang-migrate/migrate/v4/cmd/migrate: copying /var/folders/f9/d6pn7fz92w53vcpywqd_08zm0000gp/T/go-build1656176552/b001/exe/a.out: open /bin/migrate: operation not permitted

How to solve this?

Solution

$GOPATH is not set (which is fine and go will fallback to default value).

That causes $GOPATH/bin/migrate evaluate to /bin/migrate instead of its expected value – something like /home/you/go/bin/migrate (where /home/you/go is default $GOPATH).

To use the default value in case $GOPATH is not set; your go build command should call $(go env GOPATH) instead of using $GOPATH directly:

go build -tags 'mysql' -ldflags="-X main.Version=1.0.0" -o $(go env GOPATH)/bin/migrate github.com/golang-migrate/migrate/v4/cmd/migrate/

That tutorial is simply making wrong assumption that $GOPATH environment variable is always set.

Answered By – blami

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.