init
This commit is contained in:
commit
aee8bcc886
18 files changed
+960
No files matched your search
@@ -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
|
||||
}
|
||||
@@ -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"})
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user