posts-go/posts/2022-07-10-bootstrap-go.md

217 lines
6.5 KiB
Markdown
Raw Normal View History

2022-07-10 10:38:45 +00:00
# Bootstrap Go
It is hard to write bootstrap tool to quickly create Go service.
So I write this guide instead.
This is a quick checklist for me every damn time I need to write a Go service from scratch.
Also, this is my personal opinion, so feel free to comment.
## Structure
```txt
main.go
internal
2022-07-30 17:02:56 +00:00
| business
2022-07-10 10:38:45 +00:00
| | http
| | | handler.go
| | | service.go
| | | models.go
| | grpc
| | | handler.go
2022-07-30 17:02:56 +00:00
| | | models.go
| | consumer
| | | handler.go
2022-07-10 10:38:45 +00:00
| | | service.go
| | | models.go
| | service.go
| | repository.go
| | models.go
```
All business codes are inside `internal`.
2022-07-30 17:02:56 +00:00
Each business has a different directory `business`.
2022-07-10 10:38:45 +00:00
Inside each business, there are 2 handlers: `http`, `grpc`:
2022-07-30 17:02:56 +00:00
- `http` is for public APIs (Android, iOS, ... are clients).
2022-07-10 10:38:45 +00:00
- `grpc` is for internal APIs (other services are clients).
2022-07-30 17:02:56 +00:00
- `consumer` is for consuming messages from queue (Kafka, RabbitMQ, ...).
2022-07-10 10:38:45 +00:00
2022-07-30 17:02:56 +00:00
For each handler, there are usually 3 layers: `handler`, `service`, `repository`:
2022-07-10 10:38:45 +00:00
2022-07-30 17:02:56 +00:00
- `handler` interacts directly with gRPC, REST or consumer using specific codes (cookies, ...) In case gRPC, there are frameworks outside handle for us so we can write business/logic codes here too. But remember, gRPC only.
2022-07-10 10:38:45 +00:00
- `service` is where we write business/logic codes, and only business/logic codes is written here.
2022-07-30 17:10:40 +00:00
- `repository` is where we write codes which interacts with database/cache like MySQL, Redis, ...
2022-07-30 17:02:56 +00:00
- `models` is where we put all request, response, data models.
2022-07-10 10:38:45 +00:00
2022-07-30 17:10:40 +00:00
Location:
- `handler` must exist inside `grpc`, `http`, `consumer`.
- `service`, `models` can exist directly inside of `business` if both `grpc`, `http`, `consumer` has same business/logic.
- `repository` should be placed directly inside of `business`.
2022-07-10 10:38:45 +00:00
## Do not repeat!
If we have too many services, some of the logic will be overlapped.
For example, service A and service B both need to make POST call API to service C.
If service A and service B both have libs to call service C to do that API, we need to move the libs to some common pkg libs.
So in the future, service D which needs to call C will not need to copy libs to handle service C api but only need to import from common pkg libs.
Another bad practice is adapter service.
No need to write a new service if what we need is just common pkg libs.
2022-07-12 09:55:25 +00:00
## Taste on style guide
### Use functional options, but don't overuse it!
For simple struct with 1 or 2 fields, no need to use functional options.
[Example](https://go.dev/play/p/0XnOLiHuoz3):
```go
func main() {
s := NewS(WithA(1), WithB("b"))
fmt.Printf("%+v\n", s)
}
type S struct {
fieldA int
fieldB string
}
type OptionS func(s *S)
func WithA(a int) OptionS {
return func(s *S) {
s.fieldA = a
}
}
func WithB(b string) OptionS {
return func(s *S) {
s.fieldB = b
}
}
func NewS(opts ...OptionS) *S {
s := &S{}
for _, opt := range opts {
opt(s)
}
return s
}
```
In above example, I construct `s` with `WithA` and `WithB` option.
No need to pass direct field inside `s`.
2022-07-10 10:38:45 +00:00
## External libs
2022-07-18 13:53:39 +00:00
### No need `vendor`
Only need if you need something from `vendor`, to generate mock or something else.
2022-07-30 17:50:41 +00:00
### Use `build.go` to include build tools in go.mod
To easily control version of build tools.
For example `build.go`:
```go
//go:build tools
// +build tools
package main
import (
_ "github.com/golang/protobuf/protoc-gen-go"
)
```
And then in `Makefile`:
```Makefile
build:
go install github.com/golang/protobuf/protoc-gen-go
```
We always get the version of build tools in `go.mod` each time we install it.
Future contributors will not cry anymore.
2022-07-10 10:38:45 +00:00
### Don't use cli libs ([spf13/cobra](https://github.com/spf13/cobra), [urfave/cli](https://github.com/urfave/cli)) just for Go service
2022-07-30 17:02:56 +00:00
What is the point to pass many params (`do-it`, `--abc`, `--xyz`) when what we only need is start service?
2022-07-10 10:38:45 +00:00
In my case, service starts with only config, and config should be read from file or environment like [The Twelve Factors](https://12factor.net/) guide.
### Don't use [grpc-ecosystem/grpc-gateway](https://github.com/grpc-ecosystem/grpc-gateway)
Just don't.
Use [protocolbuffers/protobuf-go](https://github.com/protocolbuffers/protobuf-go), [grpc/grpc-go](https://github.com/grpc/grpc-go) for gRPC.
Write 1 for both gRPC, REST sounds good, but in the end, it is not worth it.
2022-07-10 10:58:57 +00:00
### Don't use [uber/prototool](https://github.com/uber/prototool), use [bufbuild/buf](https://github.com/bufbuild/buf)
2022-07-10 10:38:45 +00:00
2022-07-10 10:58:57 +00:00
prototool is deprecated, and buf can generate, lint, format as good as prototool.
2022-07-10 10:38:45 +00:00
2022-07-10 10:58:57 +00:00
### Use [gin-gonic/gin](https://github.com/gin-gonic/gin) for REST.
2022-07-10 10:38:45 +00:00
2022-07-10 10:58:57 +00:00
Don't use `gin.Context` when pass context from handler layer to service layer, use `gin.Context.Request.Context()` instead.
2022-07-10 10:38:45 +00:00
### If you want log, just use [uber-go/zap](https://github.com/uber-go/zap)
It is fast!
2022-07-10 10:58:57 +00:00
- Don't overuse `func (*Logger) With`. Because if log line is too long, there is a possibility that we can lost it.
2022-07-10 10:38:45 +00:00
2022-07-30 17:02:56 +00:00
- Use `MarshalLogObject` when we need to hide some field of object when log (field is long or has sensitive value)
2022-07-10 10:38:45 +00:00
2022-07-10 10:58:57 +00:00
- Don't use `Panic`. Use `Fatal` for errors when start service to check dependencies. If you really need panic level, use `DPanic`.
2022-07-21 13:54:35 +00:00
- If doubt, use `zap.Any`.
2022-07-10 10:38:45 +00:00
- Use `contextID` or `traceID` in every log lines for easily debug.
### Don't overuse ORM libs, no need to handle another layer above SQL.
Each ORM libs has each different syntax.
To learn and use those libs correctly is time consuming.
So just stick to plain SQL.
It is easier to debug when something is wrong.
But `database/sql` has its own limit.
2022-07-10 10:58:57 +00:00
For example, it is hard to get primary key after insert/update.
2022-07-10 10:38:45 +00:00
So may be you want to use ORM for those cases.
### If you want test, just use [stretchr/testify](https://github.com/stretchr/testify).
It is easy to write a suite test, thanks to testify.
Also, for mocking, there are many options out there.
Pick 1 then sleep peacefully.
2022-07-10 10:58:57 +00:00
### Replace `go fmt`, `goimports` with [mvdan/gofumpt](https://github.com/mvdan/gofumpt).
`gofumpt` provides more rules when format Go codes.
### Use [golangci/golangci-lint](https://github.com/golangci/golangci-lint).
No need to say more.
Lint or get the f out!
2022-07-12 09:55:25 +00:00
2022-07-30 17:02:56 +00:00
If you get `fieldalignment` error, use [fieldalignment](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/fieldalignment) to fix them.
```sh
# Install
go install golang.org/x/tools/go/analysis/passes/fieldalignment@latest
# Fix
fieldalignment -fix ./internal/business/*.go
```
2022-07-12 09:55:25 +00:00
## Thanks
- [Uber Go Style Guide](https://github.com/uber-go/guide/blob/master/style.md)
- [Functional options for friendly APIs](https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis)