go generate
go generate
是 Go 自带的工具。使用命令go generate
执行。go generate
是利用源代码中的注释工作的。格式如下:
//go:generate command arg1 arg2
这样在同一个目录下执行命令go generate
就会自动运行命令command arg1 arg2
。command
可以是在PATH
中的任何命令,应用非常广泛。官网提供了几种示例,见文档。stringer
命令可以为给定类型生成String
方法。
go:generate
前面只能使用//
注释,注释必须在行首,前面不能有空格且//
与go:generate
之间不能有空格!!!
makefile 中:
all:
go generate && go build .
错误码处理
通过hash保存错误码和错误描述的
package err
import "fmt"
const (
ERR_CODE_OK = 0 // success
ERR_CODE_INVALID_PARAMS = 1 // 参数无效
ERR_CODE_TIMEOUT = 2 // 请求超时
// ...
)
// 定义错误码与描述信息的映射
var mapErrDesc = map[int]string{
ERR_CODE_OK: "success",
ERR_CODE_INVALID_PARAMS: "参数无效",
ERR_CODE_TIMEOUT: "请求超时",
// ...
}
func GetErrDescByCode(code int) string {
if desc, ok := mapErrDesc[code]; ok {
return desc
}
return fmt.Sprintf("未知错误:%d", code)
}
package err
import (
"fmt"
)
type ErrCode int
const (
ERR_CODE_OK ErrCode = 0 // success
ERR_CODE_INVALID_PARAMS ErrCode = 1 // 参数无效
ERR_CODE_TIMEOUT ErrCode = 2 // 请求超时
// ...
)
// 定义错误码与描述信息的映射
var mapErrDesc = map[ErrCode]string{
ERR_CODE_OK: "success",
ERR_CODE_INVALID_PARAMS: "参数无效",
ERR_CODE_TIMEOUT: "请求超时",
// ...
}
func getErrDescByCode(code ErrCode) string {
if desc, ok := mapErrDesc[code]; ok {
return desc
}
return fmt.Sprintf("未知错误:%d", code)
}
func (err ErrCode) String() string {
return getErrDescByCode(err)
}
stringer
go get -u golang.org/x/tools/cmd/stringer
package errcode
type ErrCode int
//go:generate stringer -type ErrCode -linecomment
const (
ERR_CODE_OK ErrCode=0 //OK
ERR_CODE_INVALID_PARAMS ErrCode=1 //参数错误
ERR_CODE_TIMEOUT ErrCode =2 //请求超时
)
执行命令
go generate
会生成下面的文件
// Code generated by "stringer -type ErrCode -linecomment"; DO NOT EDIT.
package errcode
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[ERR_CODE_OK-0]
_ = x[ERR_CODE_INVALID_PARAMS-1]
_ = x[ERR_CODE_TIMEOUT-2]
}
const _ErrCode_name = "OK参数错误请求超时"
var _ErrCode_index = [...]uint8{0, 2, 14, 26}
func (i ErrCode) String() string {
if i < 0 || i >= ErrCode(len(_ErrCode_index)-1) {
return "ErrCode(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _ErrCode_name[_ErrCode_index[i]:_ErrCode_index[i+1]]
}