Skip to content

Commit 7191858

Browse files
authored
Use more go builtins (#414)
* Switch to slog instead of zerolog * IDE settings * Follow tools pattern * Trick the scanner... * Customer recovery middleware * Added middleware tests * Use std router instead of chi * Minor cleanup * Code cleanup and linting * Slightly simpler syntax * Brough back unit test check * Undo unnecessary change * Config unit tests
1 parent 8fa2579 commit 7191858

34 files changed

+1105
-320
lines changed

.editorconfig

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,10 @@ root = true
22

33
[*]
44
indent_style = space
5-
indent_size = 4
5+
indent_size = 2
66
charset = utf-8
77
trim_trailing_whitespace = true
88
insert_final_newline = true
99

1010
[{*.go,Makefile}]
1111
indent_style = tab
12-
13-
[{*.json,*.js,*.jsx,*.ts,*.tsx,*.yml,*.yaml,*.css}]
14-
indent_size = 2

.vscode/settings.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,13 @@
11
{
2+
"editor.formatOnSave": true,
23
"editor.renderWhitespace": "boundary",
4+
"go.coverOnSave": true,
5+
"go.coverageOptions": "showUncoveredCodeOnly",
6+
"go.formatTool": "goimports",
7+
"go.inlayHints.assignVariableTypes": true,
8+
"go.inlayHints.functionTypeParameters": true,
9+
"go.inlayHints.parameterNames": true,
10+
"go.inlayHints.rangeVariableTypes": true,
311
"go.lintTool": "revive",
412
"go.lintFlags": [
513
"-config=${workspaceRoot}/revive.toml"

Makefile

Lines changed: 13 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,14 @@ API_CODEGEN_FILE=api/routes.gen.go
1717
MOCKS_CODEGEN_DIR=mocks
1818
CODEGEN_FILES=$(API_CODEGEN_FILE) $(MODELS_CODEGEN_FILE) $(MOCKS_CODEGEN_DIR)
1919

20+
REPO_NAME ?= chadweimer/gomp
21+
GO_MODULE_NAME ?= github.com/$(REPO_NAME)
2022
GOOS := linux
2123
GOARCH := amd64
2224
GO_ENV=GOOS=$(GOOS) GOARCH=$(GOARCH) CGO_ENABLED=0
23-
GO_LD_FLAGS=-ldflags "-X 'github.com/chadweimer/gomp/metadata.BuildVersion=$(BUILD_VERSION)'"
25+
GO_LD_FLAGS=-ldflags "-X '$(GO_MODULE_NAME)/metadata.BuildVersion=$(BUILD_VERSION)'"
2426

2527
CONTAINER_REGISTRY ?= ghcr.io
26-
CONTAINER_IMAGE_NAME ?= chadweimer/gomp
2728

2829
GO_FILES := $(shell find . -type f -name "*.go" ! -name "*.gen.go")
2930
DB_MIGRATION_FILES := $(shell find db/migrations -type f -name "*.*")
@@ -35,10 +36,7 @@ CLIENT_FILES := $(filter-out $(shell test -d $(CLIENT_CODEGEN_DIR) && find $(CLI
3536

3637
.PHONY: install
3738
install: $(CLIENT_INSTALL_DIR)
38-
go install github.com/deepmap/oapi-codegen/v2/cmd/[email protected]
39-
go install github.com/securego/gosec/v2/cmd/[email protected]
40-
go install github.com/mgechev/[email protected]
41-
go install github.com/golang/mock/[email protected]
39+
go get ./...
4240

4341
$(CLIENT_INSTALL_DIR): static/package.json
4442
cd static && npm install --silent
@@ -52,14 +50,14 @@ uninstall:
5250
$(CLIENT_CODEGEN_DIR): $(CLIENT_INSTALL_DIR) openapi.yaml models.yaml
5351
cd static && npm run codegen
5452

55-
$(API_CODEGEN_FILE): openapi.yaml api/cfg.yaml
56-
oapi-codegen --config api/cfg.yaml openapi.yaml > $@
53+
$(API_CODEGEN_FILE): $(MODELS_CODEGEN_FILE) openapi.yaml api/cfg.yaml
54+
go generate $(GO_MODULE_NAME)/api
5755

5856
$(MODELS_CODEGEN_FILE): models.yaml models/cfg.yaml
59-
oapi-codegen --config models/cfg.yaml models.yaml > $@
57+
go generate $(GO_MODULE_NAME)/models
6058

61-
$(MOCKS_CODEGEN_DIR): $(GO_FILES)
62-
go generate ./...
59+
$(MOCKS_CODEGEN_DIR): $(GO_FILES) $(MODELS_CODEGEN_FILE)
60+
go generate $(GO_MODULE_NAME)/db $(GO_MODULE_NAME)/upload
6361

6462
# ---- LINT ----
6563

@@ -73,8 +71,8 @@ lint-client: $(CLIENT_INSTALL_DIR) $(CLIENT_CODEGEN_DIR)
7371
.PHONY: lint-server
7472
lint-server: $(CODEGEN_FILES)
7573
go vet ./...
76-
revive -config=revive.toml ./...
77-
gosec -severity medium ./...
74+
go run github.com/mgechev/revive -config=revive.toml ./...
75+
go run github.com/securego/gosec/v2/cmd/gosec -severity medium ./...
7876

7977

8078
# ---- BUILD ----
@@ -178,9 +176,9 @@ $(BUILD_DIR)/coverage/client: $(CLIENT_FILES) $(CLIENT_CODEGEN_DIR)
178176
.PHONY: docker
179177
docker: build
180178
ifndef CONTAINER_TAG
181-
docker buildx build --platform linux/amd64,linux/arm,linux/arm64 -t $(CONTAINER_REGISTRY)/$(CONTAINER_IMAGE_NAME):local .
179+
docker buildx build --platform linux/amd64,linux/arm,linux/arm64 -t $(CONTAINER_REGISTRY)/$(REPO_NAME):local .
182180
else
183-
docker buildx build --push --platform linux/amd64,linux/arm,linux/arm64 -t $(CONTAINER_REGISTRY)/$(CONTAINER_IMAGE_NAME):$(CONTAINER_TAG) .
181+
docker buildx build --push --platform linux/amd64,linux/arm,linux/arm64 -t $(CONTAINER_REGISTRY)/$(REPO_NAME):$(CONTAINER_TAG) .
184182
endif
185183

186184

api/api.go

Lines changed: 20 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,19 @@
11
package api
22

3+
//go:generate go run github.com/oapi-codegen/oapi-codegen/v2/cmd/oapi-codegen --config cfg.yaml ../openapi.yaml
4+
35
import (
46
"bytes"
57
"context"
68
"encoding/json"
79
"errors"
810
"fmt"
11+
"log/slog"
912
"net/http"
1013

1114
"github.com/chadweimer/gomp/db"
15+
"github.com/chadweimer/gomp/middleware"
1216
"github.com/chadweimer/gomp/upload"
13-
"github.com/go-chi/chi/v5"
14-
"github.com/go-chi/chi/v5/middleware"
15-
"github.com/rs/zerolog"
16-
"github.com/rs/zerolog/hlog"
17-
"github.com/rs/zerolog/log"
1817
)
1918

2019
// ---- Begin Standard Errors ----
@@ -31,10 +30,7 @@ func (k contextKey) String() string {
3130
return "gomp context key: " + string(k)
3231
}
3332

34-
const (
35-
currentUserIdCtxKey = contextKey("current-user-id")
36-
currentUserTokenCtxKey = contextKey("current-user-token")
37-
)
33+
const currentUserIdCtxKey = contextKey("current-user-id")
3834

3935
// ---- End Context Keys ----
4036

@@ -45,16 +41,14 @@ type apiHandler struct {
4541
}
4642

4743
// NewHandler returns a new instance of http.Handler
48-
func NewHandler(secureKeys []string, upl *upload.ImageUploader, db db.Driver) http.Handler {
44+
func NewHandler(secureKeys []string, upl *upload.ImageUploader, drDriver db.Driver) http.Handler {
4945
h := apiHandler{
5046
secureKeys: secureKeys,
5147
upl: upl,
52-
db: db,
48+
db: drDriver,
5349
}
5450

55-
r := chi.NewRouter()
56-
r.Use(middleware.SetHeader("Content-Type", "application/json"))
57-
r.Mount("/v1", HandlerWithOptions(NewStrictHandlerWithOptions(
51+
return HandlerWithOptions(NewStrictHandlerWithOptions(
5852
h,
5953
[]StrictMiddlewareFunc{},
6054
StrictHTTPServerOptions{
@@ -65,25 +59,26 @@ func NewHandler(secureKeys []string, upl *upload.ImageUploader, db db.Driver) ht
6559
writeErrorResponse(w, r, http.StatusInternalServerError, err)
6660
},
6761
}),
68-
ChiServerOptions{
62+
StdHTTPServerOptions{
63+
BaseURL: "/v1",
6964
Middlewares: []MiddlewareFunc{h.checkScopes},
7065
ErrorHandlerFunc: func(w http.ResponseWriter, r *http.Request, err error) {
7166
writeErrorResponse(w, r, http.StatusBadRequest, err)
7267
},
73-
}))
74-
r.NotFound(func(w http.ResponseWriter, r *http.Request) {
75-
writeErrorResponse(w, r, http.StatusNotFound, fmt.Errorf("%s is not a valid API endpoint", r.URL.Path))
76-
})
68+
})
69+
}
7770

78-
return r
71+
func logger(ctx context.Context) *slog.Logger {
72+
return middleware.GetLoggerFromContext(ctx)
7973
}
8074

81-
func writeJSONResponse(w http.ResponseWriter, r *http.Request, status int, v interface{}) {
75+
func writeJSONResponse(w http.ResponseWriter, r *http.Request, status int, v any) {
8276
buf := new(bytes.Buffer)
8377
if err := json.NewEncoder(buf).Encode(v); err != nil {
84-
hlog.FromRequest(r).UpdateContext(func(c zerolog.Context) zerolog.Context {
85-
return c.AnErr("encode-error", err).Int("original-status", status)
86-
})
78+
logger(r.Context()).
79+
Error("Failed to encode response",
80+
"error", err,
81+
"original-status", status)
8782

8883
w.WriteHeader(http.StatusInternalServerError)
8984
return
@@ -96,14 +91,8 @@ func writeJSONResponse(w http.ResponseWriter, r *http.Request, status int, v int
9691
}
9792
}
9893

99-
func logErrorToContext(ctx context.Context, err error) {
100-
log.Ctx(ctx).UpdateContext(func(c zerolog.Context) zerolog.Context {
101-
return c.Err(err)
102-
})
103-
}
104-
10594
func writeErrorResponse(w http.ResponseWriter, r *http.Request, status int, err error) {
106-
logErrorToContext(r.Context(), err)
95+
logger(r.Context()).Error("failure on request", "error", err)
10796
status = getStatusFromError(err, status)
10897
writeJSONResponse(w, r, status, http.StatusText(status))
10998
}

0 commit comments

Comments
 (0)