'Go Modules vs Package

just starting to learn about Go Modules. I have a question on importing local packages inside the same module. The example I am looking at is this repo:

https://github.com/Azure/azure-service-bus-go

The module is module github.com/Azure/azure-service-bus-go. There is a separate package inside that module, atom (but it's not a module itself). When files inside the main package import atom, they do it like this: import "github.com/Azure/azure-service-bus-go/atom" -- see queue_manager.go as an example.

What I do not quite understand -- how does GO know to look at the local atom package, as opposed to, say the one on Github? It seems confusing to me that something that is part of the module being modified is referenced by a remote/absolute URI. Is it guaranteed that if I modify the file on local disk and build I'm actually referencing the latest version as opposed to something already pushed?

As a toy exercise I tried to create a module with a non-existent Github URI and it did in fact appear that go mod tidy tried to look that up against Github, even though a local copy did in fact exist



Solution 1:[1]

The module directive in the go.mod file declares the import-path prefix for all of the packages within that module.

If you are just starting to learn about Go modules, the Create a Go module tutorial might be a good place to start.

Solution 2:[2]

I have a similar question. The answers I've seen only seem to apply to very simple directory structures. But it is easy to get complex structures in a large project. Consider a module structure like this:

quotes/
    main.go
    go.mod
    handler/
        quoteshandler/
            quoteshandler.go
    middleware/
        ...
 

To work with the local version of the packages, I use the "replace" directive at the top-level go.mod file:

quotes/go.mod:
    ...
    replace "github.com/quotes-service" => ../quotes-service

But inside the file quoteshandler.go there are import statements:

import "github.com/quotes-service/quotes/middleware"

These import dependencies are satisfied by downloading middleware from the github repository, which is not what I want. I don't know how to solve this simply. It seems one must put go.mod files with replace directives in every subdirectory of the module.

Solution 3:[3]

List item

  • A module is a collection of go packages.
  • A package is a directory of .go files. Using packages, you organize your code into reusable units.
  • We can add a module to go project or upgrade the module version.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 bcmills
Solution 2 the-typist
Solution 3 Hamed Naeemaei