Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Created August 9, 2018 19:19
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 montanaflynn/2daddba4a4a8a7c948136c3a097333fe to your computer and use it in GitHub Desktop.
Save montanaflynn/2daddba4a4a8a7c948136c3a097333fe to your computer and use it in GitHub Desktop.
A Makefile for go servers from http://azer.bike/journal/a-good-makefile-for-go/
include .env
PROJECTNAME=$(shell basename "$(PWD)")
# Go related variables.
GOBASE=$(shell pwd)
GOPATH=$(GOBASE)/vendor:$(GOBASE):/home/azer/code/golang # You can remove or change the path after last colon.
GOBIN=$(GOBASE)/bin
GOFILES=$(wildcard *.go)
# Redirect error output to a file, so we can show it in development mode.
STDERR=/tmp/.$(PROJECTNAME)-stderr.txt
# PID file will keep the process id of the server
PID=/tmp/.$(PROJECTNAME).pid
# Make is verbose in Linux. Make it silent.
MAKEFLAGS += --silent
## install: Install missing dependencies. Runs `go get` internally. e.g: make install get=github.com/foo/bar
install: go-get
## start: Start in development mode. Auto-starts when code changes.
start:
bash -c "trap 'make stop' EXIT; $(MAKE) compile start-server watch"
## stop: Stop development mode.
stop: stop-server
start-server: stop-server
@echo " > $(PROJECTNAME) is available at $(ADDR)"
@-$(GOBIN)/$(PROJECTNAME) 2>&1 & echo $$! > $(PID)
@cat $(PID) | sed "/^/s/^/ \> PID: /"
stop-server:
@-touch $(PID)
@-kill `cat $(PID)` 2> /dev/null || true
@-rm $(PID)
watch:
@yolo -i . -e vendor -e bin -c 'make compile restart-server' -a localhost:9001
restart-server: stop-server start-server
## compile: Compile the binary.
compile:
@-touch $(STDERR)
@-rm $(STDERR)
@-$(MAKE) -s go-compile 2> $(STDERR)
@cat $(STDERR) | sed -e '1s/.*/\nError:\n/' | sed 's/make\[.*/ /' | sed "/^/s/^/ /" 1>&2
## clean: Clean build files. Runs `go clean` internally.
clean:
@(MAKEFILE) go-clean
go-compile: go-clean go-get go-build
go-build:
@echo " > Building binary..."
@GOPATH=$(GOPATH) GOBIN=$(GOBIN) go build -o $(GOBIN)/$(PROJECTNAME) $(GOFILES)
go-generate:
@echo " > Generating dependency files..."
@GOPATH=$(GOPATH) GOBIN=$(GOBIN) go generate $(generate)
go-get:
@echo " > Checking if there is any missing dependencies..."
@GOPATH=$(GOPATH) GOBIN=$(GOBIN) go get $(get)
go-install:
@GOPATH=$(GOPATH) GOBIN=$(GOBIN) go install $(GOFILES)
go-clean:
@echo " > Cleaning build cache"
@GOPATH=$(GOPATH) GOBIN=$(GOBIN) go clean
.PHONY: help
all: help
help: Makefile
@echo
@echo " Choose a command run in "$(PROJECTNAME)":"
@echo
@sed -n 's/^##//p' $< | column -t -s ':' | sed -e 's/^/ /'
@echo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment