Assuming you read my post you should have the starting point for a minimal go web service. For your first project it is easier to keep all your code in one folder, in the base of your project, but at some point you want to restructure things.
All go code is organised into packages and its simply consists of several .go files. A package is the entry point to access Go code.
Best Practice to use multiple files
a. Feel free to separate you code into as many files as possible.
b. Aim to ensure it is easy to navigate your way around
c. Loosely couple sections of the service or application
Keep types close
It is often a good practice to keep the core types grouped at the top of a file.
Organise by responsibility
In other languages we organise types by models or types but in go we organise code by their functional responsibilities.
Start to Use Godoc
Godoc extracts and generates documentation for Go programs. It runs as a web server and presents the documentation as a web page.
Dont't write your business logic to main.go
- Package names should be lowercase. Don't use snake_case or camelCase.
- Avoid overly use terms like util, common, script etc
- Use singular form
- Rename should follow the same rules
*Repository Structures examples: *
```fooApp/ circle.yml Dockerfile cmd/ foosrv/ main.go foocli/ main.go pkg/ fs/ fs.go fs_test.go mock.go mock_test.go merge/ merge.go merge_test.go api/ api.go api_test.go ```
As you noticed, there is func_test.go file in the same directory. In Go, you save unit tests inside separate files with a filename ending with _test.go. Go provides go test command out of the box which executes these files and runs tests.
Common terms we use in package structure
This folder contains the main application entry point files for the project, with the directory name matching the name for the binary.
This folder contains code which is OK for other services to consume, this may include API clients, or utility functions which may be handy for other projects but don’t justify their own project.
This package holds the private library code used in your service, it is specific to the function of the service and not shared with other services.
The go. mod file defines the module's module path, which is also the import path used for the root directory, and its dependency requirements, which are the other modules needed for a successful build.
go.sum contains all the dependency check sums, and is managed by the go tools. The checksum present in go.sum file is used to validate the checksum of each of direct and indirect dependency to confirm that none of them has been modified.
``` ├── LICENSE ├── README.md ├── config.go ├── go.mod ├── go.sum ├── clientlib │ ├── lib.go │ └── lib_test.go ├── cmd │ ├── modlib-client │ │ └── main.go │ └── modlib-server │ └── main.go ├── internal │ └── auth │ ├── auth.go │ └── auth_test.go └── serverlib └── lib.go ```