Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Go Command Line tools Project structure Best practices tutorial

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "Go command line tool project structure best practice tutorial", in daily operation, I believe many people in Go command line tool project structure best practice tutorial problems have doubts, Xiaobian consulted all kinds of information, sorted out simple and easy to use operation method, hope to answer "Go command line tool project structure best practice tutorial" doubts helpful! Next, please follow the small series to learn together!

Building projects with good package design

The first best practice is to make any reusable code in a project a package. How to design package structure and the best time about package need to write a separate article, I did a share on this content, ppt link below:

https://go-pkg-structure.dev/

The benefits of putting code into packages are much greater than simply reusing code. From the perspective of project structure, putting code into separate packages helps to group code with independent functions, which makes it easier for other developers to maintain the code, which is significant for open source projects.

Separate packages make it easier to test projects. By separating features into packages, you can test individual features with fewer dependencies.

When creating and refactoring projects, I write the packages I need first, and I even create the basic project structure before I write the code.

Separate application logic from access layer logic

Another best practice that I see used a lot is to separate the application code from the access layer code, where the access code refers to the main packet and the main() method.

Go, like any other language, uses the main method as the access layer code, which is the first part of the logic to be executed when the application starts running, and it is likely that all initialization logic will be written only in the main method. It's better to put the initialization logic in the app package than to write it all in the main method.

It's better to put the initialization logic in its own package, which makes it easier to test. For example, put the Start() Stop() Shutdown() methods in the app package, and write test code to call these functions in the current package.

Here is an example of an implementation in an app package:

package app import ( "fmt" ) var ErrShutdown = fmt.Errorf("application was shutdown gracefully") func Start(...) error { // Application runtime code goes here } func Shutdown() { // Shutdown contexts, listeners, and such }

If you have both server-side and client-side code in your command-line tool project, the logic implemented in an app folder can be shared between the server and client.

However, this approach is not friendly to simple command-line applications, which may have a start-execute-stop pattern. But I still chose to put the logic in the app directory, which kept the runtime logic together and made it easier for other developers to understand the project.

What should I put in the main package?

After putting all of our apps in the app package, consider what's in the main package. Very simple, there is very little content in the main package.

In general, I would limit the main package to "only code that interacts with the user." For example, if I have both cli and server-side logic in my project, I usually put the logic for command-line parameter resolution in the main package. The binaries compiled by the server and client chlis contain different packages, and by parsing the parameters in the main package, you can create separate options for different chlis.

Other command-line applications that require interaction with users, I also tend to put them in the main package, such as:

Parsing command line arguments

User input (simple input, no involvement in core logic)

parse the configuration file

exit logic

processing signals

The following code is an example of the main method:

// main runs the command-line parsing and validations. This function will also start the application logic execution. func main() { // Parse command-line arguments var opts options args, err := flags.ParseArgs(&opts, os.Args[1:]) if err != nil { os.Exit(1) } // Convert to internal config cfg := config.New() cfg.Verbose = opts.Verbose // more taking command line options and putting them into a config struct. if opts.Pass { // ask the user for a password } // Run the App err = app.Run(cfg) if err != nil { // do stuff os.Exit(1) } }

A Recommended Project Structure

A highly recommended project structure is as follows:

internal/app -Core app functionality for internal use only

internal/pkg/ -package for internal use only

pkg/ -packages that need to be shared with external code

cmd/ -Put the main package in this directory with the app name

One of the highlights of this recommended structure is to place core code in internal/app and entry code in cmd/. This structure is friendly for projects that compile several binaries at once, such as server and cli. cmd/should contain the main method of cli, cmd/-server directory drops the main method of server side. Both can share other code under the internal/app directory.

Overall this is a good directory structure, but this directory structure does not work for me, see how I changed it.

I put the package under another path.

What I did differently from the recommendation structure in the previous paragraph was the path to the package. There are too many subdirectories in the application project structure, which is different from the standalone project structure, and I don't like organizing code in the application project structure. Too many subdirectories, I think, prevent developers from finding code that implements functionality.

Many subdirectories may be necessary for heavy projects with large code volumes, but it is best not to use this project structure for small and medium-sized projects.

I choose to put all packages at the root of the code directory, for example, I have a Parser package, its path is parser/,ssh package path is ssh/,app package path is app/.

This approach makes it easy to find packages and features because packages and code are at the first level of the project. Again, putting all packages in the first level of the directory applies to projects with a small number of packages, and if the number of packages becomes large, it is still possible to put packages under pkg/path.

I did not use internal and pkg mode

I don't think it's a good practice to put code in internal/or pkg/, mainly because it's for apps. However, there is no clear "inside" and "outside" division about the internal package of the app. For internal-only packages, many developers simply don't use best practices because "no one else uses them."

I also don't want developers to maintain code under the pkg path as if it were individual projects. In actual development, the interfaces within these packages may change as well as individual projects, so if the logic is really separated one by one, it is better to put it into individual projects.

It makes more sense for me to put all my project internals in one folder. Either in the top-level directory or in the pkg/directory.

I didn't put all my files in cmd/directory

cmd/directory does not apply to my project. I have a simple CLI application in this project, which should be easy for users to download and install. The quickest and easiest way to install is to use the go get command:

$ go get -u github.com/madflojo/efs2

I want the user to install it by simply using go get plus project url, but if you use cmd directory, you need to ask the user to add/cmd/to the url to install:

$ go get -u github.com/madflojo/efs2/cmd/efs2

This url format is messy, users also need to know how my project structure is to install. I hope the project structure makes it more convenient for others rather than more cumbersome. So I put the main.go file of this small application under the top-level folder of the project, so that users can install the application directly through the go get command, and put the function implementation of the application in the app package.

This concludes the Go command-line tools project structure best practices tutorial, hoping to resolve your doubts. Theory and practice can better match to help everyone learn, go and try it! If you want to continue learning more relevant knowledge, please continue to pay attention to the website, Xiaobian will continue to strive to bring more practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report