Golang is an open source programming language that is widely used for network service development, high-concurrency applications, and cloud services. When writing a project in golang, a good directory structure can make the project clearer and easier to maintain. Today we will discuss the settings of the golang directory structure.
Dividing projects according to functional modules is a common directory structure setting in golang. The specific method is to create multiple subdirectories in the project root directory, each subdirectory corresponding to a functional module. For example, the following example:
myproject/ ├── cmd/ │ ├── server/ │ │ ├── main.go │ ├── client/ │ │ ├── main.go ├── pkg/ │ ├── user/ │ │ ├── user.go │ ├── util/ │ │ ├── util.go ├── internal/ │ ├── auth/ │ │ ├── auth.go │ ├── db/ │ │ ├── db.go ├── vendor/ ├── go.mod ├── go.sum
In the above structure, we divide it intocmd
,pkg
,internal
according to the functional modules of the project. Three parts:
cmd
Directory stores command line tools that can be run directly, such as server programserver
and client programclient
. Thepkg
directory stores the business logic code of the project, which is divided according to functional modules, such as theuser
module and theutil
module.internal
The internal code of the project is stored in the directory, which is only used in the project and will not be used by external packages.It is worth noting that although the functions of thepkg
andinternal
directories look similar, their difference is thatpkg## The code in the # directory can be used by external packages, while the code in the
internaldirectory can only be used in this project.
myproject/ ├── cmd/ │ ├── main.go ├── pkg/ │ ├── http/ │ │ ├── server.go │ │ ├── router.go │ ├── database/ │ │ ├── db.go │ ├── log/ │ │ ├── log.go ├── vendor/ ├── go.mod ├── go.sum
cmd,
pkg, and
vendoraccording to the code type. Part: The
directory contains the entry file for the executable program, such as
main.go. The
directory is divided according to code type. For example, HTTP-related codes are placed in the
httpdirectory, and database-related codes are placed in the
databasedirectory and so on.
The directory stores the third-party packages that the project depends on.
myproject/ ├── cmd/ │ ├── main.go ├── pkg/ │ ├── models/ │ │ ├── user.go │ ├── views/ │ │ ├── index.gohtml │ ├── controllers/ │ │ ├── user.go ├── vendor/ ├── go.mod ├── go.sum
models,
views, and
controllersbased on the MVC pattern. Part:
The model layer code is stored in the directory, usually the code that deals with the database.
The view layer code is stored in the directory, usually web page templates, etc.
The directory stores the controller layer code, which is responsible for connecting the model layer and the view layer.
The above is the detailed content of golang directory settings. For more information, please follow other related articles on the PHP Chinese website!