This is a creation in Article, where the information may have evolved or changed.
Summarize the package design philosophy of Go
- Clear Purpose
- Before we get ready to design a package, we need to be clear about its purpose.
- The name of a package must clearly reflect its purpose, not just to store the code. Like the standard library of IO,HTTP,FMT These package names are very good, and the name like Util.helper,common is a negative case.
- Availability of
- Think of the real needs of the people who use this package, the use of the package must be intuitive and simple.
- In the iterative development, optimization, improvement, can not let the application of this program error.
- Prevents the need for type assertion specific types of requirements.
- Minimize the amount of code in a single package, reduce bugs, and make it easier to control.
- Portability
- Always striving for maximum portability.
- If the package is reasonable and practical, do not care too much about the opinions of others, there is no perfect package for everyone.
- Do not let the package become a single point of dependency (that is, all other packages depend on it), each package has its own design purpose, it is possible that multiple packages will have duplicate types, even if the duplicate definition does not make the package a single point of dependency, this is the API design principles.
Best practices for organization of project structures
There are two types of projects, one that builds a project that can run a program (Application project), and one that is dedicated to a suite project that is referenced by another project (Kit project).
For a suite project, the structure is organized according to the actual project purpose, and for projects that can run the program, the structure is:
├──cmd
├──internal
└──vendor
Vendor store the dependency package, internal store the package used inside the project, CMD to store the code of the running program, if the project has more than one running program, you can build subdirectories under CMD.
Note: internal can be recognized by the compiler, and packages under internal cannot be referenced by other projects.
Internal below if there are many packages, and they need to use some of the same logic, such as encryption and decryption, network requests, etc., can be built in the internal platform directory, the internal use of the package, such a structure:
├──cmd
├──internal
│└──platform
└──vendor
Note: Platform The following packages if they mature, in the future you can turn their open source into a public suite project for other people's projects to reference.
About the log output, the public suite project does not print the log because it is to be referenced by other projects, and the logic of the print log should be decided by the operational project itself.
Accompanying video: "Go language Package Design"
In-stream AD, go HTTP request library req, make HTTP request simple to extreme:https://github.com/imroc/req