What's the idiomatic way to depend on module not referenced in code (mockgen specifically)?

Viewed 316

I just switched all my existing projects to use modules. After running go mod init in each repo and adding my private personal dependencies, my go.mod looks like:

module bitbucket.org/XXXXX/my-app

replace bitbucket.org/XXXXX/utilities => ../utilities

go 1.15

require (
    <auto-generated stuff>
)

Everything is working, except mock generation, since I don't actually import mockgen directly in my code (I run it through my Makefile).

I suppose I can add it to my require blob, and make sure my Makefile invokes go mod download explicitly before running it, but I worry that it will get clobbered by the go module manager. I figure go mod tidy in particular will nuke it since it's not referenced through the code it cares about.

What's the right way to do this? I assume go get is meant to be deprecated, so I can't keep using it as I do now.

1 Answers

A popular way of doing this is by creating a file with a build tag and doing underscore imports. See this example from grpc-gateway

// +build tools

package tools

import (
    _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway"
    _ "github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger"
    _ "github.com/golang/protobuf/protoc-gen-go"
)
Related