From aee8bcc886f085da20b21cce05bcfee401205ed7 Mon Sep 17 00:00:00 2001 From: shenchangbin Date: Fri, 6 Nov 2026 15:34:35 +0800 Subject: [PATCH] init --- .env.example | 9 ++ .gitignore | 5 + Dockerfile | 18 +++ README.md | 153 ++++++++++++++++++++++++ cmd/api/main.go | 90 ++++++++++++++ configs/config.yaml | 23 ++++ enum/user.go | 8 ++ go.mod | 64 ++++++++++ go.sum | 149 +++++++++++++++++++++++ internal/config/config.go | 159 +++++++++++++++++++++++++ internal/handler/health_handler.go | 11 ++ internal/handler/user_handler.go | 82 +++++++++++++ internal/middleware/auth_middleware.go | 39 ++++++ internal/router/health.go | 11 ++ internal/router/router.go | 36 ++++++ internal/router/user.go | 14 +++ internal/service/user_service.go | 60 ++++++++++ pkg/response/response.go | 29 +++++ 18 files changed, 960 insertions(+) create mode 100644 .env.example create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 cmd/api/main.go create mode 100644 configs/config.yaml create mode 100644 enum/user.go create mode 100644 go.mod create mode 100644 go.sum create mode 100644 internal/config/config.go create mode 100644 internal/handler/health_handler.go create mode 100644 internal/handler/user_handler.go create mode 100644 internal/middleware/auth_middleware.go create mode 100644 internal/router/health.go create mode 100644 internal/router/router.go create mode 100644 internal/router/user.go create mode 100644 internal/service/user_service.go create mode 100644 pkg/response/response.go diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..ef32deb --- /dev/null +++ b/.env.example @@ -0,0 +1,9 @@ +APP_NAME=gin_layout +APP_ENV=local +APP_SERVER_PORT=8080 +APP_SERVER_MODE=debug +APP_LOG_LEVEL=info +APP_AUTH_TOKEN=replace-with-your-own-token +APP_MICRO_ETCD_ENDPOINTS=127.0.0.1:2379 +APP_MICRO_SERVICE_NAME=micro.micro_layout +APP_MICRO_TIMEOUT=3s diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b454925 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/bin/ +/coverage.out +.env +.env.local +.DS_Store diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1e9a212 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,18 @@ +FROM golang:1.27.3-alpine AS builder +WORKDIR /src +COPY proto/go.mod proto/go.sum ./proto/ +COPY gin_layout/go.mod gin_layout/go.sum ./gin_layout/ +WORKDIR /src/gin_layout +RUN go mod download +COPY proto /src/proto +COPY gin_layout /src/gin_layout +RUN CGO_ENABLED=0 go build -trimpath -o /out/api ./cmd/api + +FROM alpine:3.23 +RUN apk add --no-cache ca-certificates tzdata +WORKDIR /app +COPY --from=builder /out/api ./api +COPY gin_layout/configs/config.yaml ./configs/config.yaml +USER 65532:65532 +EXPOSE 8080 +ENTRYPOINT ["./api"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..50b5f5b --- /dev/null +++ b/README.md @@ -0,0 +1,153 @@ +# gin_layout + +基于 Gin v1.12.0 的 Go HTTP API 项目骨架,要求 Go 1.27.3 或更新版本。 +Gin 版本来源:[官方发布页](https://github.com/gin-gonic/gin/releases/tag/v1.12.0)。 + +## 目录结构 + +```text +gin_layout/ +├── cmd/api/main.go # 入口、配置加载、HTTP 服务生命周期 +├── configs/config.yaml # 可提交的非敏感默认配置 +├── internal/ +│ ├── config/config.go # Viper 加载、环境变量覆盖、强类型解析及校验 +│ ├── handler/ +│ │ ├── user_handler.go # 请求参数校验、调用 service、返回响应 +│ │ └── health_handler.go # 存活检查 +│ ├── middleware/auth_middleware.go # Bearer Token 鉴权示例 +│ ├── router/ +│ │ ├── router.go # Gin 初始化、中间件、路由分组及统一错误处理 +│ │ ├── health.go # 健康检查路由 +│ │ └── user.go # 用户路由及依赖组装 +│ └── service/user_service.go # 用户业务示例 +├── enum/user.go # 用户状态枚举 +├── pkg/response/response.go # 统一 JSON 响应 +├── .env.example +├── .gitignore +├── go.mod +├── go.sum +└── README.md +``` + +依赖方向:`main → router → handler → service`;handler 和 middleware 使用 response。 +所有路由统一放在 `internal/router` 中,新增业务路由时增加对应文件并在 `router.go` 中注册。 +service 接收标准库 `context.Context`,不依赖 Gin。 +`enum` 位于项目根目录,与 `internal`、`pkg` 同级。 + +## 启动 + +在项目根目录执行: + +本项目通过本地 `../proto` 模块调用 `../micro_layout`,请先按[父目录 README](../README.md) +启动 etcd 和 Micro。三个目录需要保持同级。 + +```sh +go mod download +cp .env.example .env +# 编辑 .env,设置自己的 APP_AUTH_TOKEN +set -a +. ./.env +set +a +go run ./cmd/api +``` + +默认监听 `:8080`,加载当前工作目录下的 `configs/config.yaml`。 + +## 配置管理 + +使用 YAML + Viper + 环境变量,加载优先级为:**环境变量 > YAML > 代码默认值**。 +配置解析为强类型 `Config` 后传入各模块,业务代码不直接读取 Viper。 + +通过 `CONFIG_FILE` 指定外部 YAML 文件(相对路径基于当前工作目录),例如: + +```sh +CONFIG_FILE=/etc/gin_layout/config.yaml APP_ENV=production APP_SERVER_MODE=release ./bin/api +``` + +生产示例要求事先由部署环境注入 `APP_AUTH_TOKEN`。 +未指定 `CONFIG_FILE` 且默认文件不存在时,可仅依赖环境变量和代码默认值运行。 +显式指定的文件不存在、文件不可读、YAML 格式错误、未知字段或类型错误都会导致启动失败。 +超时字段使用 `5s`、`1m` 等带单位的字符串,并且必须大于零。 + +| YAML 字段 | 环境变量 | 默认值 | +| --- | --- | --- | +| — | `CONFIG_FILE` | 默认搜索 `./configs/config.yaml` | +| `app.name` | `APP_NAME` | `gin_layout` | +| `app.env` | `APP_ENV` | `local` | +| `server.port` | `APP_SERVER_PORT` | `8080` | +| `server.mode` | `APP_SERVER_MODE` | `debug` | +| `server.read_header_timeout` | `APP_SERVER_READ_HEADER_TIMEOUT` | `5s` | +| `server.read_timeout` | `APP_SERVER_READ_TIMEOUT` | `10s` | +| `server.write_timeout` | `APP_SERVER_WRITE_TIMEOUT` | `10s` | +| `server.idle_timeout` | `APP_SERVER_IDLE_TIMEOUT` | `60s` | +| `server.shutdown_timeout` | `APP_SERVER_SHUTDOWN_TIMEOUT` | `10s` | +| `auth.token` | `APP_AUTH_TOKEN` | 空 | +| `log.level` | `APP_LOG_LEVEL` | `info` | + +`server.port` 范围为 1–65535;`server.mode` 支持 `debug`、`release`、`test`。 +`app.name`、`app.env` 必须非空;当 `app.env` 为 `prod` 或 `production` 时,Token 必填。 +Token 不允许包含空白字符。其他环境下 Token 为空时,受保护接口返回 503。 +显式设置的空环境变量会覆盖文件和默认值,并参与校验,不会静默回退。 + +兼容旧环境变量 `PORT`、`GIN_MODE`、`AUTH_TOKEN`,对应的 `APP_*` 变量优先级更高。 +新增配置统一使用 `APP_*`;新增字段时须在配置加载器中同步登记默认值和环境变量绑定。 + +应用日志以 JSON 输出到标准输出,包含 `service`、`env` 字段;`log.level` 支持 +`debug`、`info`、`warn`、`error` 等 slog 日志级别。Gin 请求日志仍使用自带 Logger,独立于应用日志级别。 + +### 多服务和云部署 + +每个服务维护自己的 YAML,保持统一的配置结构,通过 `APP_NAME` 标识服务。 +同一份二进制或镜像通过配置区分开发、测试和生产环境;`APP_ENV` 只是环境标识, +不会自动切换配置文件,需要配合 `CONFIG_FILE` 和环境变量指定实际配置。 + +仓库里的 YAML 只存非敏感配置,密码和 Token 由云密钥服务注入。 +使用 Kubernetes 时,可将 YAML 通过 ConfigMap 挂载,将敏感值通过 Secret 或云密钥服务注入环境变量。 +程序启动时读取配置,修改后通过重启或滚动发布生效;未来可在 `internal/config` 中扩展配置中心接入。 + +`.env.example` 是配置参考文件,程序直接读取进程环境变量,不自动加载 `.env`。 +上面的启动命令通过 shell 加载 `.env`;也可以由部署环境直接注入配置。 + +## 示例接口 + +```sh +curl http://localhost:8080/health +curl -H "Authorization: Bearer $APP_AUTH_TOKEN" http://localhost:8080/api/v1/users/1 +``` + +| 方法 | 路径 | 鉴权 | 说明 | +| --- | --- | --- | --- | +| GET | `/health` | 无 | 进程存活检查 | +| GET | `/api/v1/users/:id` | Bearer Token | 按 ID 查询示例用户 | +| POST | `/api/v1/users` | Bearer Token | 创建用户,请求体为 `{"name":"Alice"}` | + +用户数据由 Micro 管理,Gin 的 service 通过共享 proto 客户端发起 RPC。 +默认 Micro 使用内存示例并预置 ID 为 `1` 的用户,也可开启 MySQL 使用 GORM。 +`APP_MICRO_ETCD_ENDPOINTS` 指定 etcd 地址,`APP_MICRO_SERVICE_NAME` 指定服务名, +`APP_MICRO_TIMEOUT` 指定每次 RPC 的超时,默认分别为 `127.0.0.1:2379`、`micro.micro_layout`、`3s`。 +etcd 账号、密码和连接超时分别使用 `APP_MICRO_ETCD_USERNAME`、`APP_MICRO_ETCD_PASSWORD`、 +`APP_MICRO_ETCD_DIAL_TIMEOUT`;文件配置位于 `micro.etcd` 下。 +上游不可用返回 503,超时返回 504。 +鉴权使用配置中的固定 Token,不包含登录、JWT 签发或用户身份解析。 + +成功响应的 `code` 为 `0`,错误响应的 `code` 与 HTTP 状态码一致,`data` 为 `null`: + +```json +{"code":0,"message":"success","data":{"id":1,"name":"demo","status":"active"}} +``` + +非法 ID 返回 400,鉴权失败返回 401,用户或路由不存在返回 404,方法不支持返回 405。 +服务启用请求日志、panic 恢复、HTTP 超时,并在收到 SIGINT/SIGTERM 时等待在途请求完成,默认最多 10 秒,可通过配置调整。 +默认不信任代理提供的客户端 IP;部署到反向代理后可按实际网络修改 `SetTrustedProxies`。 + +## 构建与检查 + +```sh +gofmt -w cmd internal enum pkg +go test ./... +go vet ./... +go build -o bin/api ./cmd/api +APP_SERVER_MODE=release ./bin/api +``` + +当前模块路径为 `gin_layout`。发布到代码托管平台后,可将 `go.mod` 的 module 及源码导入前缀统一替换为实际仓库地址。 diff --git a/cmd/api/main.go b/cmd/api/main.go new file mode 100644 index 0000000..f9b1fea --- /dev/null +++ b/cmd/api/main.go @@ -0,0 +1,90 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net/http" + "os" + "os/signal" + "strconv" + "syscall" + + "example.com/layout/proto/micro_layout/client" + + "gin_layout/internal/config" + "gin_layout/internal/router" + "gin_layout/internal/service" +) + +func main() { + if err := run(); err != nil { + slog.Error("application stopped", "error", err) + os.Exit(1) + } +} + +func run() error { + cfg, err := config.Load() + if err != nil { + return err + } + + var level slog.Level + if err := level.UnmarshalText([]byte(cfg.Log.Level)); err != nil { + return err + } + slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{Level: level})).With( + "service", cfg.App.Name, + "env", cfg.App.Env, + )) + + microClient, err := client.NewMicroLayoutClient(cfg.Micro.Etcd, cfg.Micro.ServiceName) + if err != nil { + return err + } + defer microClient.Close() + userService := service.NewUserService(microClient.User, cfg.Micro.Timeout) + engine, err := router.New(cfg, userService) + if err != nil { + return err + } + + server := &http.Server{ + Addr: ":" + strconv.Itoa(cfg.Server.Port), + Handler: engine, + ReadHeaderTimeout: cfg.Server.ReadHeaderTimeout, + ReadTimeout: cfg.Server.ReadTimeout, + WriteTimeout: cfg.Server.WriteTimeout, + IdleTimeout: cfg.Server.IdleTimeout, + } + + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + serverErrors := make(chan error, 1) + go func() { + slog.Info("HTTP server starting", "address", server.Addr, "mode", cfg.Server.Mode) + serverErrors <- server.ListenAndServe() + }() + + select { + case err := <-serverErrors: + if errors.Is(err, http.ErrServerClosed) { + return nil + } + return fmt.Errorf("serve HTTP: %w", err) + case <-ctx.Done(): + stop() + } + + shutdownCtx, cancel := context.WithTimeout(context.Background(), cfg.Server.ShutdownTimeout) + defer cancel() + if err := server.Shutdown(shutdownCtx); err != nil { + _ = server.Close() + return fmt.Errorf("shutdown HTTP server: %w", err) + } + slog.Info("HTTP server stopped") + return nil +} diff --git a/configs/config.yaml b/configs/config.yaml new file mode 100644 index 0000000..330e24a --- /dev/null +++ b/configs/config.yaml @@ -0,0 +1,23 @@ +app: + name: gin_layout + env: local + +server: + port: 8080 + mode: debug + read_header_timeout: 5s + read_timeout: 10s + write_timeout: 10s + idle_timeout: 60s + shutdown_timeout: 10s + +log: + level: info + +micro: + service_name: micro.micro_layout + timeout: 3s + etcd: + endpoints: + - 127.0.0.1:2379 + dial_timeout: 5s diff --git a/enum/user.go b/enum/user.go new file mode 100644 index 0000000..34d7cbc --- /dev/null +++ b/enum/user.go @@ -0,0 +1,8 @@ +package enum + +type UserStatus string + +const ( + UserStatusActive UserStatus = "active" + UserStatusDisabled UserStatus = "disabled" +) diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..94b8958 --- /dev/null +++ b/go.mod @@ -0,0 +1,64 @@ +module gin_layout + +go 1.27.3 + +replace example.com/layout/proto => ../proto + +require ( + example.com/layout/proto v0.0.0 + github.com/gin-gonic/gin v1.12.0 + github.com/spf13/viper v1.21.0 + google.golang.org/grpc v1.85.0 +) + +require ( + github.com/bytedance/gopkg v0.1.3 // indirect + github.com/bytedance/sonic v1.15.0 // indirect + github.com/bytedance/sonic/loader v0.5.0 // indirect + github.com/cloudwego/base64x v0.1.6 // indirect + github.com/coreos/go-semver v0.3.1 // indirect + github.com/coreos/go-systemd/v22 v22.7.0 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.12 // indirect + github.com/gin-contrib/sse v1.1.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.30.1 // indirect + github.com/go-viper/mapstructure/v2 v2.4.0 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/goccy/go-yaml v1.19.2 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.3.0 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/quic-go/qpack v0.6.0 // indirect + github.com/quic-go/quic-go v0.59.0 // indirect + github.com/sagikazarmark/locafero v0.11.0 // indirect + github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect + github.com/spf13/afero v1.15.0 // indirect + github.com/spf13/cast v1.10.0 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.3.1 // indirect + go.etcd.io/etcd/api/v3 v3.7.3 // indirect + go.etcd.io/etcd/client/pkg/v3 v3.7.3 // indirect + go.etcd.io/etcd/client/v3 v3.7.3 // indirect + go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.27.1 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/arch v0.22.0 // indirect + golang.org/x/crypto v0.58.0 // indirect + golang.org/x/net v0.61.0 // indirect + golang.org/x/sys v0.49.0 // indirect + golang.org/x/text v0.43.0 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 // indirect + google.golang.org/protobuf v1.36.12 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..6b336d4 --- /dev/null +++ b/go.sum @@ -0,0 +1,149 @@ +github.com/bytedance/gopkg v0.1.3 h1:TPBSwH8RsouGCBcMBktLt1AymVo2TVsBVCY4b6TnZ/M= +github.com/bytedance/gopkg v0.1.3/go.mod h1:576VvJ+eJgyCzdjS+c4+77QF3p7ubbtiKARP3TxducM= +github.com/bytedance/sonic v1.15.0 h1:/PXeWFaR5ElNcVE84U0dOHjiMHQOwNIx3K4ymzh/uSE= +github.com/bytedance/sonic v1.15.0/go.mod h1:tFkWrPz0/CUCLEF4ri4UkHekCIcdnkqXw9VduqpJh0k= +github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiDd5VjlgE= +github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= +github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= +github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/coreos/go-semver v0.3.1 h1:yi21YpKnrx1gt5R+la8n5WgS0kCrsPp33dmEyHReZr4= +github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03VsM8rvUec= +github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA= +github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/gabriel-vasile/mimetype v1.4.12 h1:e9hWvmLYvtp846tLHam2o++qitpguFiYCKbn0w9jyqw= +github.com/gabriel-vasile/mimetype v1.4.12/go.mod h1:d+9Oxyo1wTzWdyVUPMmXFvp4F9tea18J8ufA774AB3s= +github.com/gin-contrib/sse v1.1.0 h1:n0w2GMuUpWDVp7qSpvze6fAu9iRxJY4Hmj6AmBOU05w= +github.com/gin-contrib/sse v1.1.0/go.mod h1:hxRZ5gVpWMT7Z0B0gSNYqqsSCNIJMjzvm6fqCz9vjwM= +github.com/gin-gonic/gin v1.12.0 h1:b3YAbrZtnf8N//yjKeU2+MQsh2mY5htkZidOM7O0wG8= +github.com/gin-gonic/gin v1.12.0/go.mod h1:VxccKfsSllpKshkBWgVgRniFFAzFb9csfngsqANjnLc= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.30.1 h1:f3zDSN/zOma+w6+1Wswgd9fLkdwy06ntQJp0BBvFG0w= +github.com/go-playground/validator/v10 v10.30.1/go.mod h1:oSuBIQzuJxL//3MelwSLD5hc2Tu889bF0Idm9Dg26cM= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= +github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk= +github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y= +github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= +github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= +github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= +github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= +github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= +github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= +github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= +github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= +github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= +github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.3.1 h1:waO7eEiFDwidsBN6agj1vJQ4AG7lh2yqXyOXqhgQuyY= +github.com/ugorji/go/codec v1.3.1/go.mod h1:pRBVtBSKl77K30Bv8R2P+cLSGaTtex6fsA2Wjqmfxj4= +go.etcd.io/etcd/api/v3 v3.7.3 h1:2tumepXe+wi7Wab64uUO71K7ISQyUWLGC1DJbbc59sY= +go.etcd.io/etcd/api/v3 v3.7.3/go.mod h1:HOR9Qn4gb/1/hVAmYprmlLpvTe6ZgfgNS9Z/+Ty65po= +go.etcd.io/etcd/client/pkg/v3 v3.7.3 h1:5zMwNu3ycrzCeA5NwOfQbxFRhqq974chq1DrYMua4QI= +go.etcd.io/etcd/client/pkg/v3 v3.7.3/go.mod h1:/OhzqYrF0U7d1NOk55VMyUQGbYD1WoIe4bJwxb47wOk= +go.etcd.io/etcd/client/v3 v3.7.3 h1:UrXcetgkuSEocaBlQlulQRJlXLEnUAHuBRbHh0lue1Q= +go.etcd.io/etcd/client/v3 v3.7.3/go.mod h1:DcPxpqcpV8WIaRi/2waPCx0/Uq8rQUweDJaDYZk1gEE= +go.mongodb.org/mongo-driver/v2 v2.5.0 h1:yXUhImUjjAInNcpTcAlPHiT7bIXhshCTL3jVBkF3xaE= +go.mongodb.org/mongo-driver/v2 v2.5.0/go.mod h1:yOI9kBsufol30iFsl1slpdq1I0eHPzybRWdyYUs8K/0= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/mock v0.6.0 h1:hyF9dfmbgIX5EfOdasqLsWD6xqpNZlXblLB/Dbnwv3Y= +go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc= +go.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= +golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= +golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= +golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= +gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= +gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= +google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 h1:lrupDmKL3p5kEX1M92oan027eCKcouzjuPbH6YBK+Rs= +google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1/go.mod h1:q/3oV3jAi5vwelxsVAprMBC8BcM2zmNe+IjRGd+9/ks= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1 h1:utmqiUzZAEINbLmRyAt1QjVkMyLQ+lvIwCpLaB1rZfw= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260817212433-ac3dfec99bb1/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= +google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= +google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= +google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..06d7a37 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,159 @@ +package config + +import ( + "errors" + "fmt" + "log/slog" + "os" + "strings" + "time" + + "example.com/layout/proto/discovery" + + "github.com/spf13/viper" +) + +type Config struct { + App AppConfig `mapstructure:"app"` + Server ServerConfig `mapstructure:"server"` + Auth AuthConfig `mapstructure:"auth"` + Log LogConfig `mapstructure:"log"` + Micro MicroConfig `mapstructure:"micro"` +} + +type MicroConfig struct { + Etcd discovery.Config `mapstructure:"etcd"` + ServiceName string `mapstructure:"service_name"` + Timeout time.Duration `mapstructure:"timeout"` +} + +type AppConfig struct { + Name string `mapstructure:"name"` + Env string `mapstructure:"env"` +} + +type ServerConfig struct { + Port int `mapstructure:"port"` + Mode string `mapstructure:"mode"` + ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout"` + ReadTimeout time.Duration `mapstructure:"read_timeout"` + WriteTimeout time.Duration `mapstructure:"write_timeout"` + IdleTimeout time.Duration `mapstructure:"idle_timeout"` + ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout"` +} + +type AuthConfig struct { + Token string `mapstructure:"token"` +} + +type LogConfig struct { + Level string `mapstructure:"level"` +} + +func Load() (Config, error) { + loader := viper.New() + loader.SetConfigType("yaml") + loader.AllowEmptyEnv(true) + + settings := []struct { + key string + fallback any + env []string + }{ + {"app.name", "gin_layout", []string{"APP_NAME"}}, + {"app.env", "local", []string{"APP_ENV"}}, + {"server.port", 8080, []string{"APP_SERVER_PORT", "PORT"}}, + {"server.mode", "debug", []string{"APP_SERVER_MODE", "GIN_MODE"}}, + {"server.read_header_timeout", "5s", []string{"APP_SERVER_READ_HEADER_TIMEOUT"}}, + {"server.read_timeout", "10s", []string{"APP_SERVER_READ_TIMEOUT"}}, + {"server.write_timeout", "10s", []string{"APP_SERVER_WRITE_TIMEOUT"}}, + {"server.idle_timeout", "60s", []string{"APP_SERVER_IDLE_TIMEOUT"}}, + {"server.shutdown_timeout", "10s", []string{"APP_SERVER_SHUTDOWN_TIMEOUT"}}, + {"auth.token", "", []string{"APP_AUTH_TOKEN", "AUTH_TOKEN"}}, + {"log.level", "info", []string{"APP_LOG_LEVEL"}}, + {"micro.etcd.endpoints", []string{"127.0.0.1:2379"}, []string{"APP_MICRO_ETCD_ENDPOINTS"}}, + {"micro.etcd.username", "", []string{"APP_MICRO_ETCD_USERNAME"}}, + {"micro.etcd.password", "", []string{"APP_MICRO_ETCD_PASSWORD"}}, + {"micro.etcd.dial_timeout", "5s", []string{"APP_MICRO_ETCD_DIAL_TIMEOUT"}}, + {"micro.service_name", "micro.micro_layout", []string{"APP_MICRO_SERVICE_NAME"}}, + {"micro.timeout", "3s", []string{"APP_MICRO_TIMEOUT"}}, + } + for _, setting := range settings { + loader.SetDefault(setting.key, setting.fallback) + if err := loader.BindEnv(append([]string{setting.key}, setting.env...)...); err != nil { + return Config{}, fmt.Errorf("bind environment variable for %s: %w", setting.key, err) + } + } + + configFile := strings.TrimSpace(os.Getenv("CONFIG_FILE")) + if configFile != "" { + loader.SetConfigFile(configFile) + } else { + loader.SetConfigName("config") + loader.AddConfigPath("./configs") + } + if err := loader.ReadInConfig(); err != nil { + var notFound viper.ConfigFileNotFoundError + if configFile != "" || !errors.As(err, ¬Found) { + return Config{}, fmt.Errorf("read configuration: %w", err) + } + } + + var cfg Config + if err := loader.UnmarshalExact(&cfg); err != nil { + return Config{}, errors.New("decode configuration: check field names and value types") + } + if err := cfg.Validate(); err != nil { + return Config{}, fmt.Errorf("validate configuration: %w", err) + } + return cfg, nil +} + +func (cfg Config) Validate() error { + if err := cfg.Micro.Etcd.Validate(); err != nil { + return err + } + if err := discovery.ValidateService(cfg.Micro.ServiceName); err != nil { + return err + } + if cfg.Micro.Timeout <= 0 { + return errors.New("micro.timeout must be greater than zero") + } + if strings.TrimSpace(cfg.App.Name) == "" || strings.TrimSpace(cfg.App.Env) == "" { + return errors.New("app.name and app.env must not be empty") + } + if cfg.Server.Port < 1 || cfg.Server.Port > 65535 { + return errors.New("server.port must be between 1 and 65535") + } + switch cfg.Server.Mode { + case "debug", "release", "test": + default: + return errors.New("server.mode must be debug, release or test") + } + timeouts := []struct { + name string + value time.Duration + }{ + {"read_header_timeout", cfg.Server.ReadHeaderTimeout}, + {"read_timeout", cfg.Server.ReadTimeout}, + {"write_timeout", cfg.Server.WriteTimeout}, + {"idle_timeout", cfg.Server.IdleTimeout}, + {"shutdown_timeout", cfg.Server.ShutdownTimeout}, + } + for _, timeout := range timeouts { + if timeout.value <= 0 { + return fmt.Errorf("server.%s must be greater than zero", timeout.name) + } + } + var level slog.Level + if err := level.UnmarshalText([]byte(cfg.Log.Level)); err != nil { + return errors.New("log.level must be a valid slog level, such as debug, info, warn or error") + } + if strings.ContainsAny(cfg.Auth.Token, " \t\r\n") { + return errors.New("auth.token must not contain whitespace") + } + if (cfg.App.Env == "prod" || cfg.App.Env == "production") && cfg.Auth.Token == "" { + return errors.New("auth.token is required in production") + } + return nil +} diff --git a/internal/handler/health_handler.go b/internal/handler/health_handler.go new file mode 100644 index 0000000..6dfe634 --- /dev/null +++ b/internal/handler/health_handler.go @@ -0,0 +1,11 @@ +package handler + +import ( + "gin_layout/pkg/response" + + "github.com/gin-gonic/gin" +) + +func Health(ctx *gin.Context) { + response.Success(ctx, gin.H{"status": "ok"}) +} diff --git a/internal/handler/user_handler.go b/internal/handler/user_handler.go new file mode 100644 index 0000000..b2adb9c --- /dev/null +++ b/internal/handler/user_handler.go @@ -0,0 +1,82 @@ +package handler + +import ( + "errors" + "net/http" + "strconv" + "strings" + "unicode/utf8" + + "gin_layout/internal/service" + "gin_layout/pkg/response" + + "github.com/gin-gonic/gin" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type UserHandler struct { + userService *service.UserService +} + +func NewUserHandler(userService *service.UserService) *UserHandler { + return &UserHandler{userService: userService} +} + +func (handler *UserHandler) GetByID(ctx *gin.Context) { + id, err := strconv.ParseInt(ctx.Param("id"), 10, 64) + if err != nil || id <= 0 { + response.Error(ctx, http.StatusBadRequest, "invalid user id") + return + } + item, err := handler.userService.GetByID(ctx.Request.Context(), id) + if err != nil { + writeUserError(ctx, err) + return + } + response.Success(ctx, item) +} + +func (handler *UserHandler) Create(ctx *gin.Context) { + var request struct { + Name string `json:"name"` + } + if err := ctx.ShouldBindJSON(&request); err != nil { + response.Error(ctx, http.StatusBadRequest, "invalid request body") + return + } + request.Name = strings.TrimSpace(request.Name) + if request.Name == "" || utf8.RuneCountInString(request.Name) > 100 { + response.Error(ctx, http.StatusBadRequest, "name must contain between 1 and 100 characters") + return + } + item, err := handler.userService.Create(ctx.Request.Context(), request.Name) + if err != nil { + writeUserError(ctx, err) + return + } + response.Success(ctx, item) +} + +func writeUserError(ctx *gin.Context, err error) { + if errors.Is(err, service.ErrUserNotFound) { + response.Error(ctx, http.StatusNotFound, "user not found") + return + } + switch status.Code(err) { + case codes.InvalidArgument: + response.Error(ctx, http.StatusBadRequest, "invalid user request") + case codes.NotFound: + response.Error(ctx, http.StatusNotFound, "user not found") + case codes.AlreadyExists: + response.Error(ctx, http.StatusConflict, "user already exists") + case codes.Unavailable: + response.Error(ctx, http.StatusServiceUnavailable, "user service unavailable") + case codes.DeadlineExceeded: + response.Error(ctx, http.StatusGatewayTimeout, "user service timeout") + case codes.Canceled: + response.Error(ctx, http.StatusRequestTimeout, "request canceled") + default: + response.Error(ctx, http.StatusBadGateway, "user service request failed") + } +} diff --git a/internal/middleware/auth_middleware.go b/internal/middleware/auth_middleware.go new file mode 100644 index 0000000..6f21157 --- /dev/null +++ b/internal/middleware/auth_middleware.go @@ -0,0 +1,39 @@ +package middleware + +import ( + "crypto/sha256" + "crypto/subtle" + "net/http" + "strings" + + "gin_layout/pkg/response" + + "github.com/gin-gonic/gin" +) + +func Auth(token string) gin.HandlerFunc { + expectedHash := sha256.Sum256([]byte(token)) + + return func(ctx *gin.Context) { + if token == "" { + response.Error(ctx, http.StatusServiceUnavailable, "authentication is not configured") + return + } + + parts := strings.Fields(ctx.GetHeader("Authorization")) + if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") { + ctx.Header("WWW-Authenticate", "Bearer") + response.Error(ctx, http.StatusUnauthorized, "unauthorized") + return + } + + actualHash := sha256.Sum256([]byte(parts[1])) + if subtle.ConstantTimeCompare(actualHash[:], expectedHash[:]) != 1 { + ctx.Header("WWW-Authenticate", "Bearer") + response.Error(ctx, http.StatusUnauthorized, "unauthorized") + return + } + + ctx.Next() + } +} diff --git a/internal/router/health.go b/internal/router/health.go new file mode 100644 index 0000000..b4dace8 --- /dev/null +++ b/internal/router/health.go @@ -0,0 +1,11 @@ +package router + +import ( + "gin_layout/internal/handler" + + "github.com/gin-gonic/gin" +) + +func registerHealthRoutes(engine *gin.Engine) { + engine.GET("/health", handler.Health) +} diff --git a/internal/router/router.go b/internal/router/router.go new file mode 100644 index 0000000..5f23e5d --- /dev/null +++ b/internal/router/router.go @@ -0,0 +1,36 @@ +package router + +import ( + "net/http" + + "gin_layout/internal/config" + "gin_layout/internal/middleware" + "gin_layout/internal/service" + "gin_layout/pkg/response" + + "github.com/gin-gonic/gin" +) + +func New(cfg config.Config, userService *service.UserService) (*gin.Engine, error) { + gin.SetMode(cfg.Server.Mode) + engine := gin.New() + engine.Use(gin.Logger(), gin.CustomRecovery(func(ctx *gin.Context, recovered any) { + response.Error(ctx, http.StatusInternalServerError, "internal server error") + })) + if err := engine.SetTrustedProxies(nil); err != nil { + return nil, err + } + engine.HandleMethodNotAllowed = true + engine.NoRoute(func(ctx *gin.Context) { + response.Error(ctx, http.StatusNotFound, "route not found") + }) + engine.NoMethod(func(ctx *gin.Context) { + response.Error(ctx, http.StatusMethodNotAllowed, "method not allowed") + }) + + registerHealthRoutes(engine) + api := engine.Group("/api/v1", middleware.Auth(cfg.Auth.Token)) + registerUserRoutes(api, userService) + + return engine, nil +} diff --git a/internal/router/user.go b/internal/router/user.go new file mode 100644 index 0000000..17b7ebc --- /dev/null +++ b/internal/router/user.go @@ -0,0 +1,14 @@ +package router + +import ( + "gin_layout/internal/handler" + "gin_layout/internal/service" + + "github.com/gin-gonic/gin" +) + +func registerUserRoutes(api *gin.RouterGroup, userService *service.UserService) { + userHandler := handler.NewUserHandler(userService) + api.POST("/users", userHandler.Create) + api.GET("/users/:id", userHandler.GetByID) +} diff --git a/internal/service/user_service.go b/internal/service/user_service.go new file mode 100644 index 0000000..b4eb0f0 --- /dev/null +++ b/internal/service/user_service.go @@ -0,0 +1,60 @@ +package service + +import ( + "context" + "errors" + "time" + + "example.com/layout/proto/micro_layout/proto/user" + "gin_layout/enum" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +var ErrUserNotFound = errors.New("user not found") + +type User struct { + ID int64 `json:"id"` + Name string `json:"name"` + Status enum.UserStatus `json:"status"` +} + +type UserService struct { + client user.UserClient + timeout time.Duration +} + +func NewUserService(client user.UserClient, timeout time.Duration) *UserService { + return &UserService{client: client, timeout: timeout} +} + +func (service *UserService) GetByID(ctx context.Context, id int64) (User, error) { + ctx, cancel := context.WithTimeout(ctx, service.timeout) + defer cancel() + response, err := service.client.QueryInfo(ctx, &user.QueryInfoRequest{Id: id}) + if err != nil { + return User{}, err + } + if !response.GetExists() { + return User{}, ErrUserNotFound + } + return fromProto(response.GetItem()) +} + +func (service *UserService) Create(ctx context.Context, name string) (User, error) { + ctx, cancel := context.WithTimeout(ctx, service.timeout) + defer cancel() + response, err := service.client.Create(ctx, &user.CreateRequest{Name: name}) + if err != nil { + return User{}, err + } + return fromProto(response.GetItem()) +} + +func fromProto(item *user.UserItem) (User, error) { + if item == nil { + return User{}, status.Error(codes.Internal, "invalid user response") + } + return User{ID: item.GetId(), Name: item.GetName(), Status: enum.UserStatus(item.GetStatus())}, nil +} diff --git a/pkg/response/response.go b/pkg/response/response.go new file mode 100644 index 0000000..e6082b5 --- /dev/null +++ b/pkg/response/response.go @@ -0,0 +1,29 @@ +package response + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +type Response struct { + Code int `json:"code"` + Message string `json:"message"` + Data any `json:"data"` +} + +func Success(ctx *gin.Context, data any) { + ctx.JSON(http.StatusOK, Response{ + Code: 0, + Message: "success", + Data: data, + }) +} + +func Error(ctx *gin.Context, status int, message string) { + ctx.AbortWithStatusJSON(status, Response{ + Code: status, + Message: message, + Data: nil, + }) +}