TExcelTAD
Home › Go Modules in Depth › Go Modules Exercises

Go Modules Exercises

Each exercise is a small piece of the logic the go command runs, written as a pure function with the calls already in place. Run the starter first: it prints placeholder answers, which shows what the calls expect. Complete the code marked TODO until the output matches the expected output, then compare with the solution. The last exercise is a real go session to fix.

Exercise 1: Parse go.sum

Topics: go.sum & the Checksum Database

Turn each go.sum line into a tuple (module, version, kind, hash), where kind is "zip" for a full-module hash and "go.mod" for a /go.mod hash. Then report the modules that have only a go.mod hash.

python · try it yourself
GO_SUM = """\
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.42.0 h1:abc=
golang.org/x/sys v0.42.0/go.mod h1:def=
rsc.io/quote v1.5.2 h1:w5fcysjrx7yqtD/aO+QwRjYZOKnaM9Uh2b40tElTs3Y=
rsc.io/quote v1.5.2/go.mod h1:LzX7hefJvL54yjefDEDHNONDjII0t9xZLPXsUe+TKr0=
"""

def parse_line(line):
    # TODO: split into module, version, hash; a version ending in /go.mod means kind "go.mod"
    return (None, None, None, None)

def gomod_only(text):
    # TODO: (module, version) pairs that have a go.mod line but no zip line, sorted
    return []

for line in GO_SUM.splitlines()[:2]:
    print(parse_line(line))
print(gomod_only(GO_SUM))
(None, None, None, None)
(None, None, None, None)
[]

Expected output:

text
('golang.org/x/sys', 'v0.6.0', 'go.mod', 'h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=')
('golang.org/x/sys', 'v0.42.0', 'zip', 'h1:abc=')
[('golang.org/x/sys', 'v0.6.0')]
Show solution
python
def parse_line(line):
    module, version, h = line.split()
    if version.endswith("/go.mod"):
        return (module, version[: -len("/go.mod")], "go.mod", h)
    return (module, version, "zip", h)

def gomod_only(text):
    entries = [parse_line(l) for l in text.splitlines() if l.strip()]
    zips = {(m, v) for m, v, kind, _ in entries if kind == "zip"}
    mods = {(m, v) for m, v, kind, _ in entries if kind == "go.mod"}
    return sorted(mods - zips)

x/sys v0.6.0 was only needed to read requirements (some dependency's go.mod mentions it); MVS selected v0.42.0, so only that version's code was downloaded.

Exercise 2: Minimal version selection

Topics: Minimal Version Selection

Implement mvs(graph, root): walk the requirement graph from root and keep the highest version of every module reached. Compare versions numerically, not as strings.

python · try it yourself
graph = {
    "app@": ["web@v1.2.0", "db@v1.0.0"],
    "web@v1.2.0": ["log@v1.4.0", "json@v1.9.0"],
    "db@v1.0.0": ["log@v1.10.0"],
    "log@v1.4.0": [],
    "log@v1.10.0": ["json@v1.2.0"],
    "json@v1.9.0": [],
    "json@v1.2.0": [],
}

def vkey(v):
    return tuple(int(x) for x in v.lstrip("v").split("."))

def mvs(graph, root):
    # TODO: depth- or breadth-first walk; selected[module] = highest version seen
    return {}

print(mvs(graph, "app@"))
{}

Expected output:

text
{'db': 'v1.0.0', 'json': 'v1.9.0', 'log': 'v1.10.0', 'web': 'v1.2.0'}
Show solution
python
def mvs(graph, root):
    selected, todo, seen = {}, [root], set()
    while todo:
        node = todo.pop()
        if node in seen:
            continue
        seen.add(node)
        for req in graph[node]:
            mod, ver = req.split("@")
            if mod not in selected or vkey(ver) > vkey(selected[mod]):
                selected[mod] = ver
            todo.append(req)
    return dict(sorted(selected.items()))

With string comparison "v1.4.0" > "v1.10.0", and log would wrongly stay at v1.4.0. Note that json v1.2.0 is reached (through log v1.10.0) but loses to v1.9.0.

Exercise 3: Is this module path valid for this version?

Topics: Semantic Import Versioning, Releasing a v2

Return "ok" or a reason: v0/v1 versions must not have a /vN suffix, v2+ versions must have the matching /vN suffix (ignore gopkg.in and +incompatible).

python · try it yourself
import re

def check(path, version):
    # TODO: compare the major version of `version` with the path's /vN suffix (if any)
    return "?"

for path, version in [("example.com/greet", "v1.4.0"), ("example.com/greet", "v2.0.0"),
                      ("example.com/greet/v2", "v2.1.0"), ("example.com/greet/v2", "v1.0.0"),
                      ("example.com/greet/v3", "v2.0.0")]:
    print(f"{path}@{version}: {check(path, version)}")
example.com/greet@v1.4.0: ?
example.com/greet@v2.0.0: ?
example.com/greet/v2@v2.1.0: ?
example.com/greet/v2@v1.0.0: ?
example.com/greet/v3@v2.0.0: ?

Expected output:

text
example.com/greet@v1.4.0: ok
example.com/greet@v2.0.0: should be v0 or v1, not v2
example.com/greet/v2@v2.1.0: ok
example.com/greet/v2@v1.0.0: should be v2, not v1
example.com/greet/v3@v2.0.0: should be v3, not v2
Show solution
python
def check(path, version):
    major = int(version.lstrip("v").split(".")[0])
    m = re.search(r"/v([2-9]|[1-9][0-9]+)
quot;, path) if m is None: return "ok" if major <= 1 else f"should be v0 or v1, not v{major}" want = int(m.group(1)) return "ok" if major == want else f"should be v{want}, not v{major}"

These are the same messages the go command prints ("invalid version: should be v0 or v1, not v2").

Exercise 4: Fix the broken module

Topics: go get & go mod tidy, Semantic Import Versioning

This app wants chi v5 but imports the wrong path, and its author hand-wrote a require line. Read the errors, then fix the session: change the import, drop the hand-written requirement, and let the go command do the rest.

bash · try it yourself
mkdir broken && cd broken
go mod init example.com/broken 2>/dev/null
cat > main.go <<'SRC'
package main

import (
	"fmt"
	"net/http/httptest"

	"github.com/go-chi/chi"
)

func main() {
	r := chi.NewRouter()
	r.Get("/", func(w http.ResponseWriter, _ *http.Request) { fmt.Fprint(w, "fixed!") })
	rec := httptest.NewRecorder()
	r.ServeHTTP(rec, httptest.NewRequest("GET", "/", nil))
	fmt.Println(rec.Body.String())
}
SRC
printf '\nrequire github.com/go-chi/chi v5.5.0\n' >> go.mod
go build . 2>&1 | head -3
go: errors parsing go.mod:
go.mod:5: require github.com/go-chi/chi: version "v5.5.0" invalid: should be v0 or v1, not v5

Expected output once fixed (the last line of the session, from go run .):

text
fixed!
Show solution

Three problems: the requirement names v5 for the v1 module path, the import uses the v1 path, and net/http is missing from the imports (the go.mod error hid that one). The fixed session:

bash
mkdir fixed && cd fixed
go mod init example.com/fixed
# main.go: import "net/http" and "github.com/go-chi/chi/v5" (package name stays chi)
go mod tidy        # finds github.com/go-chi/chi/v5 v5.5.0, writes go.mod and go.sum
go run .           # fixed!

Never type require lines: go get github.com/go-chi/chi/v5@v5.5.0 or go mod tidy would have refused the wrong path with a clear message and written a correct go.sum at the same time.

Test yourself

In Exercise 2, why must versions be compared as integer tuples?

  1. Speed
  2. As strings, "v1.4.0" sorts after "v1.10.0", so MVS would pick the wrong version
  3. Python requires it
  4. To handle pseudo-versions

Which modules in go.sum have only a /go.mod line?

  1. Replaced ones
  2. Versions whose requirements were read but whose code is not built
  3. Private ones
  4. Vendored ones