Skip to content

Instantly share code, notes, and snippets.

@udhos
Last active April 25, 2022 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save udhos/695d3be51fb4c7d151b4e252cdec3c63 to your computer and use it in GitHub Desktop.
Save udhos/695d3be51fb4c7d151b4e252cdec3c63 to your computer and use it in GitHub Desktop.
golang_layout
#!/bin/bash

module_dir=$HOME/dev/mymodule

echo
echo module_dir=$module_dir

die() {
    echo >&2 $(basename $0): $*
    exit 1
}

cd $module_dir 2>/dev/null || die "please create the dir module_dir=$module_dir"

#
# Don't confuse modules with packages.
# One module might hold many packages.
# Like this:
# module_dir/package1_dir
# module_dir/package2_dir
#

go mod init github.com/me/mymodule

mkdir -p mypkg || die "could not create dir: mypkg"

cat > mypkg/mypkg.go <<EOF
package mypkg

// Add is our function that sums two integers
func Add(x, y int) (res int) {
    return x + y
}

// Subtract subtracts two integers
func Subtract(x, y int) (res int) {
    return x - y
}
EOF

#
# Put executable at 'cmd/program'
#

cat > mypkg/mypkg_test.go <<EOF
package mypkg

import "testing"

func TestAdd(t *testing.T){

    got := Add(4, 6)
    want := 10

    if got != want {
        t.Errorf("got %q, wanted %q", got, want)
    }
}
EOF

echo
echo layout created:

find $module_dir

echo
echo running tests: go test -v ./...

go test -v ./...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment