介绍
Golint is a linter for Go source code.
- Golint 是一个源码检测工具用于检测代码规范
- Golint 不同于gofmt, Gofmt用于代码格式化
Golint会对代码做以下几个方面检查
- package注释 必须按照 “Package xxx 开头”
- package命名 不能有大写字母、下划线等特殊字符
- struct、interface等注释 必须按照指定格式开头
- struct、interface等命名
- 变量注释、命名
- 函数注释、命名
- 各种语法规范校验等
常见问题
- 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语句包含return时,后续代码不能包含在else里面
if block ends with a return statement, so drop this else and outdent its block
- errors.New(fmt.Sprintf(…)) 建议写成 fmt.Errorf(…)
should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...)
- receiver名称不能为this或self
receiver name should be a reflection of its identity; don't use generic names such as "this" or "self"
- 错误变量命名需以 Err/err 开头
error var SampleError should have name of the form ErrSample
- a+=1应该改成a++,a-=1应该改成a--
should replace num += 1 with num++
should replace num -= 1 with num--
Golint安装
mkdir -p $GOPATH/golang.org/x/ cd $GOPATH/src/golang.org/x/
git clone https://github.com/golang/lint.git
到目录$GOPATH/golang.org/x/lint/golint中运行
go install
goland配置Golint
打开setting对话框,选择工具->外部工具,刚开始是没golint的,需要添加,配置信息如下图所示
信息设置:
Program $GOPATH\src\bin\golint.exe
Arguments $FilePath$
Working directory $ProjectFileDir$
设置一个快捷键
按CTRL+L可看效果
参考资料