How to avoid making dependencies available for all packages in the module?

74 Views Asked by At

Coming form a .NET background, I am currently trying to adjust my first go project to a more go-typical project structure (similar to this). The thing I don't understand is, how to avoid dependencies accidentally creeping into packages where they do not belong.

Suppose I have a project consisting of two parts, an app called foo and a model.

  • my model has very few dependencies
  • the foo app might have dependencies to libraries for http, logging, metrics, etc.

The project might look like this:

├── go.mod
├── go.sum
├── model
│   ├── person.go
│   └── address.go
├── cmd
│   └── runfoo
│       └── main.go
└── foolib
    └── applicationlogic.go

But because the module file is at the root, go get github.com/httplib will make httplib available also for the model. This approach has drawbacks:

  • It is very easy (especially with VSCode auto-import and the like) and sometimes tempting to require httplib in the model, even though it does definitively not belong there.
  • Looking at the go.mod, I can not determine which dependencies are for the model and which are for the app.

Now, I could use very fine-grained modules and add a go.work file for developing, but that feels like it will be hard to maintain (and is not aligned with the reference structure).

How can I avoid making dependencies available for all packages and is it advisable to do so?

1

There are 1 best solutions below

2
Volker On BEST ANSWER

How can I avoid making dependencies available for all packages [?]

You cannot (with one module).

[...] and is it advisable to do so?

No, absolutely not.

The "drawbacks" you see aren't problematic at all and do not lead to any issues in practice.