diff --git a/docs/2022-07-10-bootstrap-go.html b/docs/2022-07-10-bootstrap-go.html index 25b9738..aeae758 100644 --- a/docs/2022-07-10-bootstrap-go.html +++ b/docs/2022-07-10-bootstrap-go.html @@ -15,7 +15,7 @@ internal | | service.go | | repository.go | | models.go -
All business codes are inside internal
.
Each business has a different directory business
.
Inside each business, there are 2 handlers: http
, grpc
:
http
is for public APIs (Android, iOS, ... are clients).grpc
is for internal APIs (other services are clients).consumer
is for consuming messages from queue (Kafka, RabbitMQ, ...).For each handler, there are usually 3 layers: handler
, service
, repository
:
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.service
is where we write business/logic codes, and only business/logic codes is written here.repository
is where we write codes which interacts with database/cache like MySQL, Redis, ...models
is where we put all request, response, data models.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
.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.
If I see someone using global var, I swear I shoot twice in the face.
Why?
For simple struct with 1 or 2 fields, no need to use functional options.
func main() {
+
All business codes are inside internal
.
Each business has a different directory business
.
Inside each business, there are 2 handlers: http
, grpc
:
http
is for public APIs (Android, iOS, ... are clients).grpc
is for internal APIs (other services are clients).consumer
is for consuming messages from queue (Kafka, RabbitMQ, ...).For each handler, there are usually 3 layers: handler
, service
, repository
:
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.service
is where we write business/logic codes, and only business/logic codes is written here.repository
is where we write codes which interacts with database/cache like MySQL, Redis, ...models
is where we put all request, response, data models.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
.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.
If I see someone using global var, I swear I will shoot them twice in the face.
Why?
For simple struct with 1 or 2 fields, no need to use functional options.
func main() {
s := NewS(WithA(1), WithB("b"))
fmt.Printf("%+v\n", s)
}
@@ -46,7 +46,7 @@ func NewS(opts ...OptionS) *S {
}
return s
}
-
In above example, I construct s
with WithA
and WithB
option.
No need to pass direct field inside s
.
If business logic involves calling too many APIs, but they are not depend on each other.
We can fire them parallel :)
Personally, I prefer errgroup
to WaitGroup
(https://pkg.go.dev/sync#WaitGroup).
Because I always need deal with error.
Example:
eg, egCtx := errgroup.WithContext(ctx)
+
In above example, I construct s
with WithA
and WithB
option.
No need to pass direct field inside s
.
If business logic involves calling too many APIs, but they are not depend on each other.
We can fire them parallel :)
Personally, I prefer errgroup
to WaitGroup
(https://pkg.go.dev/sync#WaitGroup).
Because I always need deal with error.
Example:
eg, egCtx := errgroup.WithContext(ctx)
eg.Go(func() error {
// Do some thing
@@ -71,14 +71,25 @@ import (
)
And then in 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.
What is the point to pass many params (do-it
, --abc
, --xyz
) when what we only need is start service?
In my case, service starts with only config, and config should be read from file or environment like The Twelve Factors guide.
Just don't.
Use protocolbuffers/protobuf-go, grpc/grpc-go for gRPC.
Write 1 for both gRPC, REST sounds good, but in the end, it is not worth it.
prototool is deprecated, and buf can generate, lint, format as good as prototool.
Don't use gin.Context
when pass context from handler layer to service layer, use gin.Context.Request.Context()
instead.
It is fast!
Don't overuse func (*Logger) With
. Because if log line is too long, there is a possibility that we can lost it.
Use MarshalLogObject
when we need to hide some field of object when log (field is long or has sensitive value)
Don't use Panic
. Use Fatal
for errors when start service to check dependencies. If you really need panic level, use DPanic
.
If doubt, use zap.Any
.
Use contextID
or traceID
in every log lines for easily debug.
Only init config in main or cmd layer.
Do not use viper.Get...
in business layer or inside business layer.
Why?
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.
For example, it is hard to get primary key after insert/update.
So may be you want to use ORM for those cases.
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.
The first is easy to use but not powerful as the later.
If you want to make sure mock func is called with correct times, use the later.
Example with matryer/moq
:
// Only gen mock if source code file is newer than mock file
+
We always get the version of build tools in go.mod
each time we install it.
Future contributors will not cry anymore.
What is the point to pass many params (do-it
, --abc
, --xyz
) when what we only need is start service?
In my case, service starts with only config, and config should be read from file or environment like The Twelve Factors guide.
Just don't.
Use protocolbuffers/protobuf-go, grpc/grpc-go for gRPC.
Write 1 for both gRPC, REST sounds good, but in the end, it is not worth it.
prototool is deprecated, and buf can generate, lint, format as good as prototool.
Don't use gin.Context
when pass context from handler layer to service layer, use gin.Context.Request.Context()
instead.
It is fast!
Don't overuse func (*Logger) With
. Because if log line is too long, there is a possibility that we can lost it.
Use MarshalLogObject
when we need to hide some field of object when log (field is long or has sensitive value)
Don't use Panic
. Use Fatal
for errors when start service to check dependencies. If you really need panic level, use DPanic
.
If doubt, use zap.Any
.
Use contextID
or traceID
in every log lines for easily debug.
Only init config in main or cmd layer.
Do not use viper.Get...
in business layer or inside business layer.
Why?
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.
For example, it is hard to get primary key after insert/update.
So may be you want to use ORM for those cases.
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.
The first is easy to use but not powerful as the later.
If you want to make sure mock func is called with correct times, use the later.
Example with matryer/moq
:
// Only gen mock if source code file is newer than mock file
// https://jonwillia.ms/2019/12/22/conditional-gomock-mockgen
//go:generate sh -c "test service_mock_generated.go -nt $GOFILE && exit 0; moq -rm -out service_mock_generated.go . Service"
-
Don't cast proto enum:
// Don't
+
Don't cast proto enum:
// Don't
a := cast.ToInt32(servicev1.ReasonCode_ABC)
// Do
a := int32(servicev1.ReasonCode_ABC)
+
type Drink int
+
+const (
+ Beer Drink = iota
+ Water
+ OrangeJuice
+)
+
go install golang.org/x/tools/cmd/stringer@latest
+
+# Run inside directory which contains Drink
+stringer -type=Drink
go fmt
, goimports
with mvdan/gofumpt.gofumpt
provides more rules when format Go codes.
No need to say more.
Lint or get the f out!
If you get fieldalignment
error, use fieldalignment to fix them.
# Install
go install golang.org/x/tools/go/analysis/passes/fieldalignment/cmd/fieldalignment@latest
diff --git a/posts/2022-07-10-bootstrap-go.md b/posts/2022-07-10-bootstrap-go.md
index 0069a78..485705b 100644
--- a/posts/2022-07-10-bootstrap-go.md
+++ b/posts/2022-07-10-bootstrap-go.md
@@ -64,7 +64,7 @@ No need to write a new service if what we need is just common pkg libs.
### Stop using global var
-If I see someone using global var, I swear I shoot twice in the face.
+If I see someone using global var, I swear I will shoot them twice in the face.
Why?
@@ -124,7 +124,7 @@ Because I always need deal with error.
Example:
-```golang
+```go
eg, egCtx := errgroup.WithContext(ctx)
eg.Go(func() error {
@@ -249,7 +249,7 @@ If you want to make sure mock func is called with correct times, use the later.
Example with `matryer/moq`:
-```golang
+```go
// Only gen mock if source code file is newer than mock file
// https://jonwillia.ms/2019/12/22/conditional-gomock-mockgen
//go:generate sh -c "test service_mock_generated.go -nt $GOFILE && exit 0; moq -rm -out service_mock_generated.go . Service"
@@ -259,7 +259,7 @@ Example with `matryer/moq`:
Don't cast proto enum:
-```golang
+```go
// Don't
a := cast.ToInt32(servicev1.ReasonCode_ABC)
@@ -267,6 +267,25 @@ a := cast.ToInt32(servicev1.ReasonCode_ABC)
a := int32(servicev1.ReasonCode_ABC)
```
+### Use [stringer](https://pkg.go.dev/golang.org/x/tools/cmd/stringer) if you want your type enum can be print as string
+
+```go
+type Drink int
+
+const (
+ Beer Drink = iota
+ Water
+ OrangeJuice
+)
+```
+
+```sh
+go install golang.org/x/tools/cmd/stringer@latest
+
+# Run inside directory which contains Drink
+stringer -type=Drink
+```
+
### Replace `go fmt`, `goimports` with [mvdan/gofumpt](https://github.com/mvdan/gofumpt).
`gofumpt` provides more rules when format Go codes.