How to use an alternate go.mod file for local development?
Asked Answered
J

2

7

Currently I am working on an API which uses Serverless Framework with Go.

I'm using the Serverless-offline plugin for local testing.

This API depends on a few other repositories (which I also maintain), which I import using the go.mod file.

However I am having a hard time refining my developer workflow.

Currently, if I want to make changes in a repository which this API depends upon, I have to alter the projects go.mod to include replace directives for the purpose of testing, but then I'm having to manually change it back for deployment to production.

Basically I'm looking for a way to include replace directives, which only get applied during local development. How has everyone else dealt with this problem?

Bonus question: Is there any way to run Serverless offline in docker? I'm finding that serverless-offline running on the bare metal is causing inconsistencies between different developers environments.

Jadda answered 12/8, 2021 at 22:2 Comment(0)
R
7

You can run go commands with an alternate go.mod file with the -modfile option:

From Build commands:

The -modfile=file.mod flag instructs the go command to read (and possibly write) an alternate file instead of go.mod in the module root directory. The file’s name must end with .mod. A file named go.mod must still be present in order to determine the module root directory, but it is not accessed. When -modfile is specified, an alternate go.sum file is also used: its path is derived from the -modfile flag by trimming the .mod extension and appending .sum.

Create a local.go.mod file with the necessary replace directive for development and build, for example, with:

go build -modfile=local.go.mod ./...
Raouf answered 21/8, 2021 at 19:19 Comment(0)
M
2

The easiest way to do this in Go 1.18 or later is using the new Go workspaces feature. See

Essentially, use go work init to create a go.work file, that can contain local replacement directives, outside the scope of your go.mod.

Moreville answered 11/7, 2023 at 4:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.