Skip to content

Instantly share code, notes, and snippets.

@damienstanton
Last active January 30, 2020 15:04
Show Gist options
  • Select an option

  • Save damienstanton/d44a6d2e10656c825b51a5d45fd13220 to your computer and use it in GitHub Desktop.

Select an option

Save damienstanton/d44a6d2e10656c825b51a5d45fd13220 to your computer and use it in GitHub Desktop.
Go module-based project generator

This simple bash/zsh function automates a make-based Go project that uses modules (No GOPATH muckery required).

Installation

Copy the goproject file somewhere on your $PATH and chmod +x it, or copy the function definition into your own bash/zsh script.

Usage

This is little more than a wrapper around running go mod init <etc>, writing a few files so you don't have to think about it. Expected outputs are shown in comments following each command.

  • Set up a new project
$ goproject github.com/damienstanton smoketest
# go: creating new go.mod: module github.com/damienstanton/smoketest
  • Run unit tests (the previous command automatically cds you into the new project)
$ make test
# === RUN   TestNothing
# --- PASS: TestNothing (0.00s)
# PASS
# coverage: 0.0% of statements
# ok      github.com/damienstanton/smoketest     0.126s
  • Build the program
$ make build
# ls bin/
# smoketest
  • Run the program (automatically builds)
$ make run
# smoketest OK

Gotchas

  • Don't end your project name with _test, as this breaks the ability to run/test.
#!/usr/bin/env zsh
goproject () {
# Usage:
# goproject <import_path_to_be_created> <project_name>
# i.e. goproject github.com/damienstanton smoke_test
coord=$1
project=$2
mkdir $project && cd $project
go mod init $coord/$project
cat <<ENDGOFILE > $project.go
package main
import "fmt"
func main() { fmt.Println("$project OK") }
ENDGOFILE
cat <<ENDGOTESTFILE > ${project}_test.go
package main
import "testing"
func TestNothing(t *testing.T) {
if 1 != 1 { t.Fatal("not possible") }
}
ENDGOTESTFILE
cat <<ENDMAKE > Makefile
.PHONY: default
default: build test run
.PHONY: build
build:
@go build -o bin/$project
.PHONY: test
test:
@go test -v -cover
.PHONY: _run
_run:
@go run $project.go
.PHONY: run
run: build _run
ENDMAKE
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment