Go Packages

Module Initialization

Create a new Go module
go mod init github.com/evanusmodestus/netcheck
go.mod structure
module github.com/evanusmodestus/netcheck

go 1.22

require (
    github.com/spf13/cobra v1.8.0
)

go mod init creates go.mod, which tracks the module path, Go version, and dependencies.

Package Organization

One package per directory
// Project layout:
// netcheck/
// +-- go.mod
// +-- main.go          // package main
// +-- cmd/
// |   +-- root.go      // package cmd
// +-- internal/
// |   +-- scanner/
// |       +-- scanner.go  // package scanner
// +-- pkg/
//     +-- report/
//         +-- report.go   // package report

// main.go
package main

import "github.com/evanusmodestus/netcheck/cmd"

func main() {
    cmd.Execute()
}

internal/ is special: packages under it are only importable by code within the parent module. Use it for implementation details.

Dependency Management

Essential go mod commands
go get github.com/spf13/cobra@latest     # add dependency
go get github.com/spf13/cobra@v1.8.0     # specific version
go get -u ./...                           # update all
go mod tidy                               # add missing, remove unused
go mod vendor                             # vendor locally
go mod why github.com/some/dep            # why is this included?
go mod graph | grep cobra                 # dependency graph

go mod tidy is your cleanup command. Run it before committing. go.sum contains cryptographic checksums — commit it alongside go.mod.

Visibility Rules

Capitalization is access control
package scanner

// Exported — visible outside the package
type Result struct {
    Host string
    Port int
    Open bool
}

// Unexported — only visible within package scanner
type scanConfig struct {
    timeout time.Duration
    retries int
}

// Exported function
func Scan(host string, ports []int) []Result { ... }

// Unexported function
func resolveHost(name string) (string, error) { ... }

Capitalized = exported. Lowercase = unexported. No other access modifiers exist.

Build & Run

Essential go commands
go run main.go                                  # run without binary
go run .                                        # run package in cwd
go build -o netcheck .                          # build binary
GOOS=linux GOARCH=amd64 go build -o netcheck .  # cross-compile
go install github.com/user/tool@latest          # install to GOPATH/bin
gofmt -w .                                      # format all code
go vet ./...                                    # static analysis

Cross-compilation is built in — set GOOS and GOARCH. No toolchain installation needed. go vet catches printf format mismatches, unreachable code, and shadowed variables.