Search code examples
goyamlbackendgo-cobrago-build

What does this command do 'GOFLAGS=-mod=mod'?


I am trying to make a Taskfile.yml file for building go application, but I can't quite understand the need of "GOFLAGS=-mod=mod" command before go build main.go.

reference: https://dev.to/aurelievache/learning-go-by-examples-part-3-create-a-cli-app-in-go-1h43


Solution

  • So there are two things here

    • GOFLAGS
      • this is nothing but an environment variable(if you don't understand what an environment variable is, think of it like a value that can be accessed by any process in your current environment. These values are maintained by the OS).
      • So this GOFLAGS variable has a space separated list of flags that will automatically be passed to the appropriate go commands.
      • The flag we are setting here is mod, this flag is applicable to the go build command and may not be applicable to other go commands.
      • If you are curious how go does this, refer to this change request
      • Since we are mentioning this as part of the command, this environment variable is temporarily set and is not actually exported.
    • what does setting -mod=mod flag, actually do during go build?
      • The -mod flag controls whether go.mod may be automatically updated and whether the vendor directory is used.
      • -mod=mod tells the go command to ignore the vendor directory and to automatically update go.mod, for example, when an imported package is not provided by any known module.
      • Refer this.

    Therefore

    GOFLAGS="-mod=mod" go build main.go
    

    is equivalent to

    go build -mod=mod main.go