go generate

go generate是 Go 自带的工具。使用命令go generate执行。go generate是利用源代码中的注释工作的。格式如下:

  1. //go:generate command arg1 arg2

这样在同一个目录下执行命令go generate就会自动运行命令command arg1 arg2command可以是在PATH中的任何命令,应用非常广泛。官网提供了几种示例,见文档
stringer命令可以为给定类型生成String方法。

  1. go:generate前面只能使用//注释,注释必须在行首,前面不能有空格且//go:generate之间不能有空格!!!

makefile 中:

  1. all:
  2. go generate && go build .

错误码处理

通过hash保存错误码和错误描述的

  1. package err
  2. import "fmt"
  3. const (
  4. ERR_CODE_OK = 0 // success
  5. ERR_CODE_INVALID_PARAMS = 1 // 参数无效
  6. ERR_CODE_TIMEOUT = 2 // 请求超时
  7. // ...
  8. )
  9. // 定义错误码与描述信息的映射
  10. var mapErrDesc = map[int]string{
  11. ERR_CODE_OK: "success",
  12. ERR_CODE_INVALID_PARAMS: "参数无效",
  13. ERR_CODE_TIMEOUT: "请求超时",
  14. // ...
  15. }
  16. func GetErrDescByCode(code int) string {
  17. if desc, ok := mapErrDesc[code]; ok {
  18. return desc
  19. }
  20. return fmt.Sprintf("未知错误:%d", code)
  21. }
  1. package err
  2. import (
  3. "fmt"
  4. )
  5. type ErrCode int
  6. const (
  7. ERR_CODE_OK ErrCode = 0 // success
  8. ERR_CODE_INVALID_PARAMS ErrCode = 1 // 参数无效
  9. ERR_CODE_TIMEOUT ErrCode = 2 // 请求超时
  10. // ...
  11. )
  12. // 定义错误码与描述信息的映射
  13. var mapErrDesc = map[ErrCode]string{
  14. ERR_CODE_OK: "success",
  15. ERR_CODE_INVALID_PARAMS: "参数无效",
  16. ERR_CODE_TIMEOUT: "请求超时",
  17. // ...
  18. }
  19. func getErrDescByCode(code ErrCode) string {
  20. if desc, ok := mapErrDesc[code]; ok {
  21. return desc
  22. }
  23. return fmt.Sprintf("未知错误:%d", code)
  24. }
  25. func (err ErrCode) String() string {
  26. return getErrDescByCode(err)
  27. }

stringer

  1. go get -u golang.org/x/tools/cmd/stringer
  1. package errcode
  2. type ErrCode int
  3. //go:generate stringer -type ErrCode -linecomment
  4. const (
  5. ERR_CODE_OK ErrCode=0 //OK
  6. ERR_CODE_INVALID_PARAMS ErrCode=1 //参数错误
  7. ERR_CODE_TIMEOUT ErrCode =2 //请求超时
  8. )

执行命令

  1. go generate

会生成下面的文件

  1. // Code generated by "stringer -type ErrCode -linecomment"; DO NOT EDIT.
  2. package errcode
  3. import "strconv"
  4. func _() {
  5. // An "invalid array index" compiler error signifies that the constant values have changed.
  6. // Re-run the stringer command to generate them again.
  7. var x [1]struct{}
  8. _ = x[ERR_CODE_OK-0]
  9. _ = x[ERR_CODE_INVALID_PARAMS-1]
  10. _ = x[ERR_CODE_TIMEOUT-2]
  11. }
  12. const _ErrCode_name = "OK参数错误请求超时"
  13. var _ErrCode_index = [...]uint8{0, 2, 14, 26}
  14. func (i ErrCode) String() string {
  15. if i < 0 || i >= ErrCode(len(_ErrCode_index)-1) {
  16. return "ErrCode(" + strconv.FormatInt(int64(i), 10) + ")"
  17. }
  18. return _ErrCode_name[_ErrCode_index[i]:_ErrCode_index[i+1]]
  19. }