一. Golint介紹
Golint is a linter for Go source code.
Golint 是一個源碼檢測工具用於檢測代碼規範
Golint 不同於gofmt, Gofmt用於代碼格式化
Golint會對代碼做以下幾個方面檢查
package註釋 必須按照 “Package xxx 開頭”
package命名 不能有大寫字母、下劃線等特殊字符
struct、interface等註釋 必須按照指定格式開頭
struct、interface等命名
變量註釋、命名
函數註釋、命名
各種語法規範校驗等
二. Golint安裝
go get -u github.com/golang/lint/golint
ls $GOPATH/bin (可以發現已經有golint可執行文件)
三. Golint使用
golint檢測代碼有2種方式
golint file
golint directory
golint校驗常見的問題如下所示
don't use ALL_CAPS in Go names; use CamelCase
不能使用下劃線命名法,使用駝峰命名法
exported function Xxx should have comment or be unexported
外部可見程序結構體、變量、函數都需要註釋
var statJsonByte should be statJSONByte
var taskId should be taskID
通用名詞要求大寫
iD/Id -> ID
Http -> HTTP
Json -> JSON
Url -> URL
Ip -> IP
Sql -> SQL
don't use an underscore in package name
don't use MixedCaps in package name; xxXxx should be xxxxx
包命名統一小寫不使用駝峰和下劃線
comment on exported type Repo should be of the form "Repo ..." (with optional leading article)
註釋第一個單詞要求是註釋程序主體的名稱,註釋可選不是必須的
type name will be used as user.UserModel by other packages, and that stutters; consider calling this Model
外部可見程序實體不建議再加包名前綴
if block ends with a return statement, so drop this else and outdent its block
if語句包含return時,後續代碼不能包含在else裡面
should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...)
errors.New(fmt.Sprintf(…)) 建議寫成 fmt.Errorf(…)
receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"
receiver名稱不能為this或self
error var SampleError should have name of the form ErrSample
錯誤變量命名需以 Err/err 開頭
should replace num += 1 with num++
should replace num -= 1 with num--
a+=1應該改成a++,a-=1應該改成a–
四. Goland配置golint
新增tool: Goland -> Tools -> External Tools 新建一個tool 配置如下
新增快捷鍵: Goland -> Tools -> Keymap -> External Tools -> External Tools -> golint
右鍵新增快捷鍵
使用: 打開Go文件,然後使用快捷鍵就可以進行代碼檢測了
有golint的輸出日誌說明存在代碼不規範的地方,需要進行修改
五. gitlab提交限制
為了保證項目代碼規範,我們可以在gitlab上做一層約束限制,當代碼提交到gitlab的時候先做golint校驗,校驗不通過則不讓提交代碼。
我們可以為Go項目創建gitlab CI流程,通過.gitlab-ci.yml配置CI流程會自動使用govet進行代碼靜態檢查、gofmt進行代碼格式化檢查、golint進行代碼規範檢查、gotest進行單元測試
例如go-common項目 .gitlab.yml文件如下,相關的腳本可以查看scripts
# gitlab CI/CD pipeline配置文件
# 默認使用本地定製過的帶有golint的golang鏡像
image: golang:custom
stages:
- test
before_script:
- mkdir -p /go/src/gitlab.local.com/golang
- ln -s `pwd` /go/src/gitlab.local.com/golang/go-common && cd /go/src/gitlab.local.com/golang/go-common
# test stage
# job 1 test go vet
job_govet:
stage: test
/> - bash ./scripts/ci-govet-check.sh
tags:
- dev
# job 2 test go fmt
job_gofmt:
stage: test
/> - bash ./scripts/ci-gofmt-check.sh
tags:
- dev
# job 3 test go lint
job_golint:
stage: test
/> - bash ./scripts/ci-golint-check.sh
tags:
- dev
# job 4 test go unit test
job_unit:
stage: test
/> - bash ./scripts/ci-gotest-check.sh
tags:
- dev
閱讀更多 零一零一 的文章