Go语言代码规范

参考资料

https://github.com/smallnest/go-best-practices

代码规范

  • 驼峰命名法

    变量等采用驼峰命名法

  • 包名

    包名不要用下划线和驼峰, 应采用小写, 并谨慎的采用清晰明了的简写, 参照https://blog.golang.org/package-names, 节选如下:

    Good package names are short and clear. They are lower case, with no under_scores or mixedCaps. They are often simple nouns, such as:

    • time (provides functionality for measuring and displaying time)
    • list (implements a doubly linked list)
    • http (provides HTTP client and server implementations)

    The style of names typical of another language might not be idiomatic in a Go program. Here are two examples of names that might be good style in other languages but do not fit well in Go:

    • computeServiceClient
    • priority_queue

    A Go package may export several types and functions. For example, a compute package could export a Client type with methods for using the service as well as functions for partitioning a compute task across several clients. Abbreviate judiciously. Package names may be abbreviated when the abbreviation is familiar to the programmer. Widely-used packages often have compressed names:

    • strconv (string conversion)
    • syscall (system call)
    • fmt (formatted I/O)

    On the other hand, if abbreviating a package name makes it ambiguous or unclear, don’t do it. Don’t steal good names from the user. Avoid giving a package a name that is commonly used in client code. For example, the buffered I/O package is called bufio, not buf, since buf is a good variable name for a buffer.

文档及注释

通用注释

参照:

https://blog.golang.org/godoc-documenting-go-code https://juejin.im/entry/5b8e6a77e51d4538b7767eda

需要注意的是:

  • 注释写在代码的上面, 例如函数定义的上方, 和Python不太一样
  • 对外暴露的函数变量等必需要写注释
  • 注释必需以变量名称开头

API注释

swagger相关知识参照https://juejin.im/post/5b05138cf265da0ba7701a37

gin框架也有对应的swagger工具, https://github.com/swaggo/gin-swagger, 经实践不好用

参照另一篇文章: 用swagger给Go-Web项目写API文档

工具

  • godoc

    godoc -http=:6060

    输入这个命令即可在浏览器访问文档, 访问某个项目的文档则在地址后面加上项目路径, 例如http://localhost:6060/src/gitlab.luojilab.com/rock/chaos/

  • golint

    在项目路径下输入golint命令, 可检查代码规范, 例如驼峰命名法, 是否有注释 注意: 这个命令只会检查当前路径下的文件, 不会检查子路径下的文件 这个库已过期不再维护, 可以用staticcheck

  • staticcheck