feat: update

This commit is contained in:
ivamp 2024-06-16 00:55:25 +08:00
parent 8ea6ead6cc
commit a589e615e7
25 changed files with 187 additions and 164 deletions

View File

@ -1,4 +1,4 @@
package providers package config
import ( import (
"github.com/joho/godotenv" "github.com/joho/godotenv"

View File

@ -1,7 +1,8 @@
package providers package ent
import ( import (
"errors" "errors"
"framework_v2/internal/app/logger"
_ "github.com/lib/pq" _ "github.com/lib/pq"
"go.uber.org/zap" "go.uber.org/zap"
) )
@ -17,7 +18,7 @@ func InitEnt() {
err = errors.New("ent not implemented") err = errors.New("ent not implemented")
if err != nil { if err != nil {
Logger.Fatal("failed opening connection to db", zap.Error(err)) logger.Logger.Fatal("failed opening connection to db", zap.Error(err))
} }
// //
//if err := Ent.Schema.Create( //if err := Ent.Schema.Create(

View File

@ -1,4 +1,4 @@
package access package facades
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"

View File

@ -1,10 +1,11 @@
package providers package gin
import ( import (
"fmt" "fmt"
"framework_v2/internal/access" "framework_v2/internal/app/facades"
"framework_v2/internal/consts" "framework_v2/internal/app/helpers"
"framework_v2/internal/helper" "framework_v2/internal/app/user"
http2 "framework_v2/internal/middleware/http"
ginzap "github.com/gin-contrib/zap" ginzap "github.com/gin-contrib/zap"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http" "net/http"
@ -15,9 +16,9 @@ import (
func InitGin() { func InitGin() {
gin.SetMode(gin.ReleaseMode) gin.SetMode(gin.ReleaseMode)
access.Router = gin.New() facades.Router = gin.New()
access.Router.Use(ginzap.Ginzap(access.Logger, time.RFC3339, true)) facades.Router.Use(ginzap.Ginzap(facades.Logger, time.RFC3339, true))
//access.Router.Use(gin.Recovery()) //access.Router.Use(gin.Recovery())
//access.Router.Use(ginzap.RecoveryWithZap(access.Logger, true)) //access.Router.Use(ginzap.RecoveryWithZap(access.Logger, true))
} }
@ -44,31 +45,31 @@ func InitGin() {
//} //}
func GET(relativePath string, handlers ...interface{}) { func GET(relativePath string, handlers ...interface{}) {
access.Router.GET(relativePath, func(c *gin.Context) { facades.Router.GET(relativePath, func(c *gin.Context) {
doHandler(c, handlers...) doHandler(c, handlers...)
}) })
} }
func POST(relativePath string, handlers ...interface{}) { func POST(relativePath string, handlers ...interface{}) {
access.Router.POST(relativePath, func(c *gin.Context) { facades.Router.POST(relativePath, func(c *gin.Context) {
doHandler(c, handlers...) doHandler(c, handlers...)
}) })
} }
func PUT(relativePath string, handlers ...interface{}) { func PUT(relativePath string, handlers ...interface{}) {
access.Router.PUT(relativePath, func(c *gin.Context) { facades.Router.PUT(relativePath, func(c *gin.Context) {
doHandler(c, handlers...) doHandler(c, handlers...)
}) })
} }
func PATCH(relativePath string, handlers ...interface{}) { func PATCH(relativePath string, handlers ...interface{}) {
access.Router.PATCH(relativePath, func(c *gin.Context) { facades.Router.PATCH(relativePath, func(c *gin.Context) {
doHandler(c, handlers...) doHandler(c, handlers...)
}) })
} }
func DELETE(relativePath string, handlers ...interface{}) { func DELETE(relativePath string, handlers ...interface{}) {
access.Router.DELETE(relativePath, func(c *gin.Context) { facades.Router.DELETE(relativePath, func(c *gin.Context) {
doHandler(c, handlers...) doHandler(c, handlers...)
}) })
} }
@ -80,7 +81,7 @@ func doHandler(c *gin.Context, handlers ...interface{}) {
if c.Writer.Written() { if c.Writer.Written() {
return return
} else { } else {
helper.ResponseError(c, http.StatusBadRequest, ErrEmptyResponse) helpers.ResponseError(c, http.StatusBadRequest, http2.ErrEmptyResponse)
} }
return return
@ -103,15 +104,15 @@ func wrapHandler(c *gin.Context, f interface{}) {
switch argType { switch argType {
case reflect.TypeOf((*gin.Context)(nil)): case reflect.TypeOf((*gin.Context)(nil)):
argValue = reflect.ValueOf(c) argValue = reflect.ValueOf(c)
case reflect.TypeOf((*consts.User)(nil)): case reflect.TypeOf((*user.User)(nil)):
userInfo := DIJWTAuth(c) userInfo := http2.DIJWTAuth(c)
if userInfo == nil { if userInfo == nil {
helper.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken) helpers.ResponseError(c, http.StatusUnauthorized, http2.ErrNotValidToken)
return return
} }
argValue = reflect.ValueOf(userInfo) argValue = reflect.ValueOf(userInfo)
default: default:
helper.ResponseError(c, http.StatusBadRequest, fmt.Errorf("invalid argument type: %s", argType.String())) helpers.ResponseError(c, http.StatusBadRequest, fmt.Errorf("invalid argument type: %s", argType.String()))
return return
} }

View File

@ -1,4 +1,4 @@
package helper package helpers
func Offset(page int, pageSize int) int { func Offset(page int, pageSize int) int {
offset := (page - 1) * pageSize offset := (page - 1) * pageSize

View File

@ -1,12 +1,12 @@
package helper package helpers
import ( import (
"framework_v2/internal/consts" "framework_v2/internal/app/response"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func ResponseMessage(c *gin.Context, code int, message string, data interface{}) { func ResponseMessage(c *gin.Context, code int, message string, data interface{}) {
c.JSON(code, &consts.BaseResponse{ c.JSON(code, &response.BaseResponse{
Message: message, Message: message,
Code: code, Code: code,
Data: data, Data: data,
@ -15,7 +15,7 @@ func ResponseMessage(c *gin.Context, code int, message string, data interface{})
} }
func Response(c *gin.Context, code int, data interface{}) { func Response(c *gin.Context, code int, data interface{}) {
c.JSON(code, &consts.BaseResponse{ c.JSON(code, &response.BaseResponse{
Code: code, Code: code,
Data: data, Data: data,
}) })
@ -23,7 +23,7 @@ func Response(c *gin.Context, code int, data interface{}) {
} }
func ResponseError(c *gin.Context, code int, err error) { func ResponseError(c *gin.Context, code int, err error) {
c.JSON(code, &consts.BaseResponse{ c.JSON(code, &response.BaseResponse{
Error: err.Error(), Error: err.Error(),
Code: code, Code: code,
}) })

View File

@ -1,14 +1,17 @@
package providers package jobs
import "github.com/hibiken/asynq" import (
"framework_v2/internal/app/config"
"github.com/hibiken/asynq"
)
var AsynQClient *asynq.Client var AsynQClient *asynq.Client
var AsynQServer *asynq.Server var AsynQServer *asynq.Server
func getAsynQRedisOpt() asynq.RedisClientOpt { func getAsynQRedisOpt() asynq.RedisClientOpt {
return asynq.RedisClientOpt{ return asynq.RedisClientOpt{
Addr: Config.Redis.Addr, Addr: config.Config.Redis.Addr,
Password: Config.Redis.Pass, Password: config.Config.Redis.Pass,
DB: 0, DB: 0,
} }
} }

View File

@ -1,9 +1,9 @@
package providers package jwks
import ( import (
"context"
"errors" "errors"
"framework_v2/internal/consts" "framework_v2/internal/app/config"
"framework_v2/internal/app/logger"
"github.com/MicahParks/keyfunc/v3" "github.com/MicahParks/keyfunc/v3"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
"time" "time"
@ -28,16 +28,16 @@ func InitJwksRefresh() {
} }
func RefreshJWKS() { func RefreshJWKS() {
Logger.Info("Refreshing JWKS...") logger.Logger.Info("Refreshing JWKS...")
var err error var err error
Jwks, err = keyfunc.NewDefault([]string{Config.JWKS.Url}) Jwks, err = keyfunc.NewDefault([]string{config.Config.JWKS.Url})
if err != nil { if err != nil {
Logger.Error("Failed to create JWK Set from resource at the given URL.\nError: " + err.Error()) logger.Logger.Error("Failed to create JWK Set from resource at the given URL.\nError: " + err.Error())
} }
Logger.Info("JWKS refreshed.") logger.Logger.Info("JWKS refreshed.")
} }
func ParseJWT(jwtB64 string) (*jwt.Token, error) { func ParseJWT(jwtB64 string) (*jwt.Token, error) {
@ -50,13 +50,3 @@ func ParseJWT(jwtB64 string) (*jwt.Token, error) {
return token, err return token, err
} }
func GetAuthFromCtx(ctx context.Context) *consts.UserTokenInfo {
auth := ctx.Value(consts.UserTokenInfoKey)
if auth == nil {
return nil
}
return auth.(*consts.UserTokenInfo)
}

View File

@ -1,7 +1,7 @@
package providers package logger
import ( import (
"framework_v2/internal/access" "framework_v2/internal/app/facades"
"go.uber.org/zap" "go.uber.org/zap"
) )
@ -19,5 +19,5 @@ func InitLogger() {
panic(err) panic(err)
} }
access.Logger = Logger facades.Logger = Logger
} }

View File

@ -1,8 +1,9 @@
package providers package redis
import "C" import "C"
import ( import (
"framework_v2/internal/access" "framework_v2/internal/app/config"
"framework_v2/internal/app/facades"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"golang.org/x/net/context" "golang.org/x/net/context"
) )
@ -11,8 +12,8 @@ var Redis *redis.Client
func InitRedis() { func InitRedis() {
Redis = redis.NewClient(&redis.Options{ Redis = redis.NewClient(&redis.Options{
Addr: Config.Redis.Addr, Addr: config.Config.Redis.Addr,
Password: Config.Redis.Pass, Password: config.Config.Redis.Pass,
DB: 0, // use default DB DB: 0, // use default DB
}) })
@ -24,5 +25,5 @@ func InitRedis() {
panic(err) panic(err)
} }
access.Redis = Redis facades.Redis = Redis
} }

View File

@ -1,4 +1,4 @@
package consts package response
type BaseResponse struct { type BaseResponse struct {
Message string `json:"message"` Message string `json:"message"`

View File

@ -0,0 +1,14 @@
package server
import (
"framework_v2/internal/app/facades"
"framework_v2/internal/routes"
)
func InitHttp() {
if facades.Router == nil {
panic("You must call InitGin() before InitHttp()")
}
routes.InitApiRoutes()
}

View File

@ -1,4 +1,4 @@
package consts package user
type UserTokenInfo struct { type UserTokenInfo struct {
Exp int `json:"exp"` Exp int `json:"exp"`

View File

@ -1,9 +1,13 @@
package cmd package cmd
import ( import (
"framework_v2/internal/access" "framework_v2/internal/app/config"
internalHttp "framework_v2/internal/http" "framework_v2/internal/app/facades"
"framework_v2/internal/providers" "framework_v2/internal/app/gin"
"framework_v2/internal/app/jobs"
"framework_v2/internal/app/jwks"
"framework_v2/internal/app/logger"
"framework_v2/internal/app/server"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -11,27 +15,27 @@ var httpCommand = &cobra.Command{
Use: "http", Use: "http",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
providers.InitConfig() config.InitConfig()
providers.InitLogger() logger.InitLogger()
// you should uncommit it after run make ent // you should uncommit it after run make ent
//providers.InitEnt() //providers.InitEnt()
//providers.InitRedis() //providers.InitRedis()
providers.InitJwksRefresh() jwks.InitJwksRefresh()
providers.InitAsynQClient() jobs.InitAsynQClient()
providers.InitGin() gin.InitGin()
internalHttp.InitHttp() server.InitHttp()
StartHttp() StartHttp()
}, },
} }
func StartHttp() { func StartHttp() {
if providers.Config.HTTP.ListenAddr == "" { if config.Config.HTTP.ListenAddr == "" {
providers.Config.HTTP.ListenAddr = "0.0.0.0:8080" config.Config.HTTP.ListenAddr = "0.0.0.0:8080"
} }
providers.Logger.Info("Http Server listening at " + providers.Config.HTTP.ListenAddr) logger.Logger.Info("Http Server listening at " + config.Config.HTTP.ListenAddr)
err := access.Router.Run(providers.Config.HTTP.ListenAddr) err := facades.Router.Run(config.Config.HTTP.ListenAddr)
if err != nil { if err != nil {
panic("failed to listen: " + err.Error()) panic("failed to listen: " + err.Error())
} }

View File

@ -7,9 +7,12 @@ import (
"entgo.io/ent/dialect/sql/schema" "entgo.io/ent/dialect/sql/schema"
"errors" "errors"
"fmt" "fmt"
"framework_v2/internal/app/config"
"framework_v2/internal/app/ent"
"framework_v2/internal/app/logger"
//entmigrate "framework_v2/internal/ent/migrate" //entmigrate "framework_v2/internal/ent/migrate"
"framework_v2/internal/migrations" "framework_v2/internal/migrations"
"framework_v2/internal/providers"
"github.com/golang-migrate/migrate/v4" "github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres" _ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file" _ "github.com/golang-migrate/migrate/v4/source/file"
@ -26,9 +29,9 @@ var dsnCommand = &cobra.Command{
Short: "生成 DSN", Short: "生成 DSN",
Long: "生成 DSN", Long: "生成 DSN",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
providers.InitConfig() config.InitConfig()
fmt.Print(providers.Config.DB.Driver + "://" + providers.Config.DB.DSN) fmt.Print(config.Config.DB.Driver + "://" + config.Config.DB.DSN)
}, },
} }
@ -37,9 +40,9 @@ var migrateCommand = &cobra.Command{
Short: "迁移数据库", Short: "迁移数据库",
Long: "适用于生产环境的数据库迁移", Long: "适用于生产环境的数据库迁移",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
providers.InitConfig() config.InitConfig()
providers.InitEnt() ent.InitEnt()
providers.InitLogger() logger.InitLogger()
RunMigrate() RunMigrate()
}, },
} }
@ -49,9 +52,9 @@ var createMigrateCommand = &cobra.Command{
Short: "新建迁移", Short: "新建迁移",
Long: "从 internal/ent 中新建迁移。在这之前,需要运行 go generate ./internal/ent", Long: "从 internal/ent 中新建迁移。在这之前,需要运行 go generate ./internal/ent",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
providers.InitConfig() config.InitConfig()
providers.InitEnt() ent.InitEnt()
providers.InitLogger() logger.InitLogger()
generateMigration() generateMigration()
}, },
} }
@ -60,7 +63,7 @@ var createMigrateCommand = &cobra.Command{
func RunMigrate() { func RunMigrate() {
source, err := httpfs.New(http.FS(migrations.MigrationFS), ".") source, err := httpfs.New(http.FS(migrations.MigrationFS), ".")
mig, err := migrate.NewWithSourceInstance("httpfs", source, providers.Config.DB.Driver+"://"+providers.Config.DB.DSN) mig, err := migrate.NewWithSourceInstance("httpfs", source, config.Config.DB.Driver+"://"+config.Config.DB.DSN)
if err != nil { if err != nil {
panic(err) panic(err)

View File

@ -1,8 +1,13 @@
package cmd package cmd
import ( import (
"framework_v2/internal/providers" "framework_v2/internal/app/config"
"framework_v2/internal/providers/interceptor" "framework_v2/internal/app/ent"
"framework_v2/internal/app/jobs"
"framework_v2/internal/app/jwks"
"framework_v2/internal/app/logger"
"framework_v2/internal/app/redis"
grpc2 "framework_v2/internal/middleware/grpc"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -16,36 +21,36 @@ var rpcCommand = &cobra.Command{
Use: "serve", Use: "serve",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
providers.InitConfig() config.InitConfig()
providers.InitLogger() logger.InitLogger()
providers.InitEnt() ent.InitEnt()
providers.InitRedis() redis.InitRedis()
providers.InitJwksRefresh() jwks.InitJwksRefresh()
providers.InitAsynQClient() jobs.InitAsynQClient()
StartSpiderService() StartSpiderService()
}, },
} }
func StartSpiderService() { func StartSpiderService() {
if providers.Config.GRPC.GrpcListenAddr == "" { if config.Config.GRPC.GrpcListenAddr == "" {
providers.Config.GRPC.GrpcListenAddr = "0.0.0.0:8081" config.Config.GRPC.GrpcListenAddr = "0.0.0.0:8081"
} }
lis, err := net.Listen("tcp", providers.Config.GRPC.GrpcListenAddr) lis, err := net.Listen("tcp", config.Config.GRPC.GrpcListenAddr)
if err != nil { if err != nil {
panic("failed to listen: " + err.Error()) panic("failed to listen: " + err.Error())
} }
providers.Logger.Info("Server listening at " + providers.Config.GRPC.GrpcListenAddr) logger.Logger.Info("Server listening at " + config.Config.GRPC.GrpcListenAddr)
var opts = []grpc.ServerOption{ var opts = []grpc.ServerOption{
grpc.ChainUnaryInterceptor( grpc.ChainUnaryInterceptor(
logging.UnaryServerInterceptor(interceptor.ZapLogInterceptor()), logging.UnaryServerInterceptor(grpc2.ZapLogInterceptor()),
auth.UnaryServerInterceptor(interceptor.JwtAuth), auth.UnaryServerInterceptor(grpc2.JwtAuth),
), ),
grpc.ChainStreamInterceptor( grpc.ChainStreamInterceptor(
logging.StreamServerInterceptor(interceptor.ZapLogInterceptor()), logging.StreamServerInterceptor(grpc2.ZapLogInterceptor()),
auth.StreamServerInterceptor(interceptor.JwtAuth), auth.StreamServerInterceptor(grpc2.JwtAuth),
), ),
} }
grpcServer := grpc.NewServer(opts...) grpcServer := grpc.NewServer(opts...)

View File

@ -2,7 +2,11 @@ package cmd
import ( import (
"fmt" "fmt"
"framework_v2/internal/providers" "framework_v2/internal/app/config"
"framework_v2/internal/app/ent"
"framework_v2/internal/app/jobs"
"framework_v2/internal/app/logger"
"framework_v2/internal/app/redis"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"time" "time"
@ -12,11 +16,11 @@ var scheduleCommand = &cobra.Command{
Use: "schedule", Use: "schedule",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
providers.InitConfig() config.InitConfig()
providers.InitLogger() logger.InitLogger()
providers.InitEnt() ent.InitEnt()
providers.InitRedis() redis.InitRedis()
providers.InitAsynQClient() jobs.InitAsynQClient()
runSchedule() runSchedule()
}, },
@ -24,7 +28,7 @@ var scheduleCommand = &cobra.Command{
func runSchedule() { func runSchedule() {
if providers.Config.DebugMode.Enable { if config.Config.DebugMode.Enable {
fmt.Println("调试模式开启,直接触发。") fmt.Println("调试模式开启,直接触发。")
// RUN JOB // RUN JOB
return return

View File

@ -1,7 +1,11 @@
package cmd package cmd
import ( import (
"framework_v2/internal/providers" "framework_v2/internal/app/config"
"framework_v2/internal/app/ent"
"framework_v2/internal/app/jobs"
"framework_v2/internal/app/logger"
"framework_v2/internal/app/redis"
"github.com/hibiken/asynq" "github.com/hibiken/asynq"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"log" "log"
@ -11,11 +15,11 @@ var workerCommand = &cobra.Command{
Use: "worker", Use: "worker",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
providers.InitConfig() config.InitConfig()
providers.InitLogger() logger.InitLogger()
providers.InitEnt() ent.InitEnt()
providers.InitRedis() redis.InitRedis()
providers.InitAsynQServer() jobs.InitAsynQServer()
runWorker() runWorker()
}, },
@ -27,7 +31,7 @@ func runWorker() {
//mux.HandleFunc(tasks.DocumentChunkTask, tasks.HandleDocumentChunkTask) //mux.HandleFunc(tasks.DocumentChunkTask, tasks.HandleDocumentChunkTask)
//mux.HandleFunc(tasks.DocumentImportTask, tasks.HandleDocumentImportTask) //mux.HandleFunc(tasks.DocumentImportTask, tasks.HandleDocumentImportTask)
if err := providers.AsynQServer.Run(mux); err != nil { if err := jobs.AsynQServer.Run(mux); err != nil {
log.Fatal(err) log.Fatal(err)
} }

View File

@ -2,7 +2,7 @@ package user
import ( import (
"fmt" "fmt"
"framework_v2/internal/consts" "framework_v2/internal/app/user"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
@ -13,7 +13,7 @@ import (
// //
//} //}
func CurrentUser(c *gin.Context, user *consts.User) { func CurrentUser(c *gin.Context, user *user.User) {
fmt.Println("CurrentUser", user) fmt.Println("CurrentUser", user)
c.JSON(200, gin.H{ c.JSON(200, gin.H{
"IP": c.ClientIP(), "IP": c.ClientIP(),

View File

@ -1,14 +0,0 @@
package http
import (
"framework_v2/internal/access"
"framework_v2/internal/providers"
)
func InitHttp() {
if access.Router == nil {
panic("You must call InitGin() before InitHttp()")
}
providers.InitApiRoutes()
}

View File

@ -1,9 +1,11 @@
package interceptor package grpc
import ( import (
"context" "context"
"framework_v2/internal/consts" "framework_v2/internal/app/config"
"framework_v2/internal/providers" "framework_v2/internal/app/jwks"
"framework_v2/internal/app/logger"
"framework_v2/internal/app/user"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/auth"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
@ -18,14 +20,14 @@ func JwtAuth(ctx context.Context) (context.Context, error) {
} }
sub := "anonymous" sub := "anonymous"
var jwtIdToken *consts.UserTokenInfo var jwtIdToken *user.UserTokenInfo
if providers.Config.DebugMode.Enable { if config.Config.DebugMode.Enable {
jwtIdToken = &consts.UserTokenInfo{ jwtIdToken = &user.UserTokenInfo{
Sub: sub, Sub: sub,
} }
} else { } else {
token, err := providers.ParseJWT(tokenString) token, err := jwks.ParseJWT(tokenString)
if err != nil { if err != nil {
return nil, status.Errorf(codes.Unauthenticated, "invalid auth token: %v", err) return nil, status.Errorf(codes.Unauthenticated, "invalid auth token: %v", err)
} }
@ -36,7 +38,7 @@ func JwtAuth(ctx context.Context) (context.Context, error) {
err = mapstructure.Decode(token.Claims, &jwtIdToken) err = mapstructure.Decode(token.Claims, &jwtIdToken)
if err != nil { if err != nil {
providers.Logger.Error("Failed to map token claims to JwtIDToken struct.\nError: " + err.Error()) logger.Logger.Error("Failed to map token claims to JwtIDToken struct.\nError: " + err.Error())
return nil, err return nil, err
} }
} }

View File

@ -1,9 +1,9 @@
package interceptor package grpc
import ( import (
"context" "context"
"fmt" "fmt"
"framework_v2/internal/providers" "framework_v2/internal/app/logger"
"github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging" "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"go.uber.org/zap" "go.uber.org/zap"
) )
@ -28,17 +28,17 @@ func ZapLogInterceptor() logging.Logger {
} }
} }
logger := providers.Logger.WithOptions(zap.AddCallerSkip(1)).With(f...) log := logger.Logger.WithOptions(zap.AddCallerSkip(1)).With(f...)
switch lvl { switch lvl {
case logging.LevelDebug: case logging.LevelDebug:
logger.Debug(msg) log.Debug(msg)
case logging.LevelInfo: case logging.LevelInfo:
logger.Info(msg) log.Info(msg)
case logging.LevelWarn: case logging.LevelWarn:
logger.Warn(msg) log.Warn(msg)
case logging.LevelError: case logging.LevelError:
logger.Error(msg) log.Error(msg)
default: default:
panic(fmt.Sprintf("unknown level %v", lvl)) panic(fmt.Sprintf("unknown level %v", lvl))
} }

View File

@ -1,9 +1,12 @@
package providers package http
import ( import (
"errors" "errors"
"framework_v2/internal/consts" "framework_v2/internal/app/config"
"framework_v2/internal/helper" "framework_v2/internal/app/facades"
"framework_v2/internal/app/helpers"
"framework_v2/internal/app/jwks"
"framework_v2/internal/app/user"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/mitchellh/mapstructure" "github.com/mitchellh/mapstructure"
"net/http" "net/http"
@ -20,47 +23,47 @@ var (
const AnonymousUser = "anonymous" const AnonymousUser = "anonymous"
// DIJWTAuth 用于注入到方法签名中。我觉得下面的代码以后可以优化。 // DIJWTAuth 用于注入到方法签名中。我觉得下面的代码以后可以优化。
func DIJWTAuth(c *gin.Context) *consts.User { func DIJWTAuth(c *gin.Context) *user.User {
var sub = AnonymousUser var sub = AnonymousUser
var jwtIdToken = &consts.User{} var jwtIdToken = &user.User{}
if Config.DebugMode.Enable { if config.Config.DebugMode.Enable {
jwtIdToken.Token.Sub = sub jwtIdToken.Token.Sub = sub
} else { } else {
// get authorization header // get authorization header
authorization := c.Request.Header.Get("Authorization") authorization := c.Request.Header.Get("Authorization")
if authorization == "" { if authorization == "" {
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError) helpers.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
return nil return nil
} }
authSplit := strings.Split(authorization, " ") authSplit := strings.Split(authorization, " ")
if len(authSplit) != 2 { if len(authSplit) != 2 {
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError) helpers.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
return nil return nil
} }
if authSplit[0] != "Bearer" { if authSplit[0] != "Bearer" {
helper.ResponseError(c, http.StatusUnauthorized, ErrNotBearerType) helpers.ResponseError(c, http.StatusUnauthorized, ErrNotBearerType)
return nil return nil
} }
token, err := ParseJWT(authSplit[1]) token, err := jwks.ParseJWT(authSplit[1])
if err != nil { if err != nil {
helper.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError) helpers.ResponseError(c, http.StatusUnauthorized, ErrJWTFormatError)
return nil return nil
} }
sub, err = token.Claims.GetSubject() sub, err = token.Claims.GetSubject()
if err != nil { if err != nil {
helper.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken) helpers.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken)
return nil return nil
} }
err = mapstructure.Decode(token.Claims, &jwtIdToken.Token) err = mapstructure.Decode(token.Claims, &jwtIdToken.Token)
if err != nil { if err != nil {
Logger.Error("Failed to map token claims to JwtIDToken struct.\nError: " + err.Error()) facades.Logger.Error("Failed to map token claims to JwtIDToken struct.\nError: " + err.Error())
helper.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken) helpers.ResponseError(c, http.StatusUnauthorized, ErrNotValidToken)
return nil return nil
} }
} }

View File

@ -1,9 +0,0 @@
package providers
import (
"framework_v2/internal/http/controllers/user"
)
func InitApiRoutes() {
GET("/", MiddlewareJSONResponse, user.CurrentUser)
}

View File

@ -0,0 +1,11 @@
package routes
import (
"framework_v2/internal/app/gin"
"framework_v2/internal/http/controllers/user"
"framework_v2/internal/middleware/http"
)
func InitApiRoutes() {
gin.GET("/", http.MiddlewareJSONResponse, user.CurrentUser)
}