Golang anatomy

From wikinotes

This page is a general getting started in go.

Project Structure

  go.mod                   # module name, requirements
  main.go                  # 'main' package's 'main()' function is optional CLI entrypoint
  printer.go               # other 'main' package src are in toplevel dir

  internal/                # exported symbols from internal packages are only exposed within 'myproject'
    logger/                # subpackage
    math/                  # subpackage


// myproject/go.mod

module example.com/x/myproject

go 1.18


// myproject/main.go

package main

import (

ErrEnvVarUnset = errors.New("Environment Variable Not Set")

func getUserName() (name string, err error) {
    username := os.Getenv("USER")
    if username == "" {
        return nil, ErrEnvVarUnset;
    return username, nil;

func main() {
    logger.Info.Println("a log statement");

    name, err := getUserName();   // type inference
    if err != nil {

    var gid int16;                // declare var
    gid = 1000;                   // assign typed var 

    fmt.Printf("logged in as user: %s, with gid %i", name, gid);


// myproject/internal/logger/logger.go

package logger

var Info *log.Logger

func init() {
    Info = log.New(io.Stderr, "INFO: ", log.Ldate|log.Ltime|log.Llongfile)


# project management
go mod init foo.net/x/my-project  # create new project
$GOPRIVATE                        # glob-matches projects not published to public registry

# requirements
go get example.com/module@latest  # add/update requirement (latest)
go get example.com/module v1.1.1  # add/update/downgrade to target version

# package management
go install example.com/module@latest  # install tool

# documentation
go doc io       # functions/constants on 'io'
go doc io.File  # methods on 'io.File'

# build/run main package
go run .

# test

# build management
go build
go clean
go install