使用 Makefile 輕鬆管理 Go 項目:提高開發效率的利器

一、介紹

1、make 介紹

2、Makefile 介紹

3、win10 安裝 make

4、規則介紹

[target] ... : [prerequisites] ...
<tab>[command]
    ...
    ...
build:
  CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o xx

二、makefile 基本使用

1、main.go

package main
import (
  "fmt"
  "net/http"
)
func main() {
  http.HandleFunc("/", hello)
  server := &http.Server{
    Addr: ":8888",
  }
  fmt.Println("server startup...")
  if err := server.ListenAndServe(); err != nil {
    fmt.Printf("server startup failed, err:%v\n", err)
  }
}
func hello(w http.ResponseWriter, _ *http.Request) {
  w.Write([]byte("hello v5blog.cn!"))
}

2、示例

.PHONY: all build run gotool clean help
# 編譯後的項目名
BINARY="xxx"
# 如果make後面不加任何參數,默認執行all
all: gotool build
build:
  CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o ${BINARY}
run:
  @go run ./main.go
  #@go run ./main.go conf/config.yaml
gotool:
  go fmt ./
  go vet ./
clean:
  @if [ -f ${BINARY} ] ; then rm ${BINARY} ; fi
help:
  @echo "make - 格式化 Go 代碼, 並編譯生成二進制文件"
  @echo "make build - 編譯 Go 代碼, 生成二進制文件"
  @echo "make run - 直接運行 Go 代碼"
  @echo "make clean - 移除二進制文件和 vim swap files"
  @echo "make gotool - 運行 Go 工具 'fmt' and 'vet'"

3、使用

**三、完整
**

.PHONY: all build run gotool clean help
BINARY="bluebell"
all: gotool build
build:
  CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w" -o ./bin/${BINARY}
run:
  @go run ./main.go conf/config.yaml
gotool:
  go fmt ./
  go vet ./
clean:
  @if [ -f ${BINARY} ] ; then rm ${BINARY} ; fi
help:
  @echo "make - 格式化 Go 代碼, 並編譯生成二進制文件"
  @echo "make build - 編譯 Go 代碼, 生成二進制文件"
  @echo "make run - 直接運行 Go 代碼"
  @echo "make clean - 移除二進制文件和 vim swap files"
  @echo "make gotool - 運行 Go 工具 'fmt' and 'vet'"
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/Fxd7hDtjRWEeBTxk3ba9fg