diff --git a/.github/workflows/go.yml b/.github/workflows/go.yml index e58ba3e..0c16a4c 100644 --- a/.github/workflows/go.yml +++ b/.github/workflows/go.yml @@ -18,10 +18,6 @@ jobs: with: go-version: "1.22" - - name: Install - run: go install github.com/swaggo/swag/cmd/swag@latest - - # 生成swag信息 # build项目 - name: Build - run: swag init && go build + run: go build diff --git a/.gitignore b/.gitignore index 295fb2b..b060df0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ .idea +.vscode + *.db tmp diff --git a/README.md b/README.md index 51a73dd..5f257e3 100644 --- a/README.md +++ b/README.md @@ -18,14 +18,19 @@ - 获取/查看接口文档 - 拉取项目后,安装[go swag](https://github.com/swaggo/gin-swagger)组件,执行以下命令生成swag文档。 + 拉取项目后,安装[go swag](https://github.com/swaggo/gin-swagger)组件,根据以下提示生成swag文档并查看。 ```sh - swag init + # generate documentation for auth endpoint. + # (debug mode) after generation, open http://BASEURL/swagger/auth/index.html to check. + swag i -g auth.go -dir router,api/auth --instanceName auth --pd + + # generate documentation for api/v1 endpoint. + # (debug mode) after generation, open http://BASEURL/swagger/v1/index.html to check. + swag i -g v1.go -dir router,api/v1 --instanceName v1 --pd + ``` - 然后可以**在debug模式下**前往http:///swagger/index.html查看。 - ## 参考 diff --git a/api/auth.go b/api/auth/auth.go similarity index 62% rename from api/auth.go rename to api/auth/auth.go index 9f60d0f..7221e91 100644 --- a/api/auth.go +++ b/api/auth/auth.go @@ -1,14 +1,22 @@ -package api +package auth import ( "auth-server/middleware" "auth-server/model" + "github.com/gin-gonic/gin" ) -type AuthApi struct{} +type Apis struct{} -func (AuthApi) Login(c *gin.Context) { +// Login 用户登录 +// @description 用户登录 +// @version 1.0 +// @tags 身份认证 +// @BasePath /auth +// @router /login [post] +// @param bodyParams body model.LoginUser true "请求体参数" +func (Apis) Login(c *gin.Context) { var param model.LoginUser if err := c.ShouldBindJSON(¶m); err != nil { middleware.Fail(c, model.ErrParam.AddErr(err)) @@ -16,10 +24,9 @@ func (AuthApi) Login(c *gin.Context) { } err := authService.Login(param, c) middleware.Auto(c, err, nil) - return } -func (AuthApi) Register(c *gin.Context) { +func (Apis) Register(c *gin.Context) { var param model.User if err := c.ShouldBindJSON(¶m); err != nil { middleware.Fail(c, model.ErrParam.AddErr(err)) @@ -27,10 +34,9 @@ func (AuthApi) Register(c *gin.Context) { } err := authService.Register(¶m) middleware.Auto(c, err, nil) - return } -func (AuthApi) Logout(c *gin.Context) { +func (Apis) Logout(c *gin.Context) { err := authService.Logout(c) middleware.Auto(c, err, nil) } diff --git a/api/auth/init.go b/api/auth/init.go new file mode 100644 index 0000000..42c2253 --- /dev/null +++ b/api/auth/init.go @@ -0,0 +1,5 @@ +package auth + +import "auth-server/services" + +var authService services.AuthService diff --git a/api/init.go b/api/init.go deleted file mode 100644 index 310a4f3..0000000 --- a/api/init.go +++ /dev/null @@ -1,10 +0,0 @@ -package api - -import ( - "auth-server/services" -) - -var ( - userService services.UserService - authService services.AuthService -) diff --git a/api/v1/init.go b/api/v1/init.go new file mode 100644 index 0000000..b2da657 --- /dev/null +++ b/api/v1/init.go @@ -0,0 +1,5 @@ +package v1 + +import "auth-server/services" + +var userService services.UserService diff --git a/api/user.go b/api/v1/user.go similarity index 64% rename from api/user.go rename to api/v1/user.go index 1c12dea..7615f86 100644 --- a/api/user.go +++ b/api/v1/user.go @@ -1,4 +1,4 @@ -package api +package v1 import ( "auth-server/middleware" @@ -8,22 +8,23 @@ import ( "github.com/gin-gonic/gin" ) -type GetUserParam struct { - Id string `uri:"id" binding:"required"` -} - type UserApi struct{} -// @title 查询用户 -// @router /users/:id [get] -// @version 1.0 +// GetUser 查询用户 // @description 依据用户的id,查询用户的信息 -// @summary 查询用户信息 -// @accept json -// @param id path string true "用户id" +// @version 1.0 +// @tags 用户模块 +// @BasePath /api/v1 +// @router /users/{id} [get] +// @param pathParams path model.GetUserParams true "路径参数" // @success 200 {object} model.User func (UserApi) GetUser(c *gin.Context) { - params, _, _ := middleware.Validate[GetUserParam, any, any](c) + var params model.GetUserParams + + if err := c.ShouldBindUri(¶ms); err != nil { + middleware.Fail(c, model.ErrParam.AddErr(err)) + return + } userId, err := strconv.ParseInt(params.Id, 10, 64) if err != nil { @@ -32,7 +33,6 @@ func (UserApi) GetUser(c *gin.Context) { } user, err1 := userService.GetUser(userId) middleware.Auto(c, err1, user) - return } func (UserApi) UpdateUser(gin *gin.Context) { diff --git a/common/log.go b/common/log.go index d38062f..75393bf 100644 --- a/common/log.go +++ b/common/log.go @@ -3,15 +3,15 @@ package common import ( "bytes" "fmt" + "github.com/sirupsen/logrus" "gopkg.in/natefinch/lumberjack.v2" - "path" ) var Log = logrus.New() type LumberHook struct { - logger *lumberjack.Logger + Logger *lumberjack.Logger } func (hook LumberHook) Levels() []logrus.Level { @@ -35,7 +35,7 @@ func (hook LumberHook) Fire(entry *logrus.Entry) (err error) { writeLine = entry.Message + "\n" } - _, err = hook.logger.Write([]byte(writeLine)) + _, err = hook.Logger.Write([]byte(writeLine)) return } @@ -59,23 +59,3 @@ func (f MyFormatter) Format(entry *logrus.Entry) ([]byte, error) { return b.Bytes(), nil } - -func InitLog(logPath, appName string) { - - // 设置日志输出格式 - Log.SetFormatter(&MyFormatter{}) - - logFileName := path.Join(logPath, appName) - // 使用滚动压缩方式记录日志 - lumberLog := &lumberjack.Logger{ - Filename: logFileName, //日志文件位置 - MaxSize: 1, // 单文件最大容量,单位是MB - MaxBackups: 3, // 最大保留过期文件个数 - MaxAge: 1, // 保留过期文件的最大时间间隔,单位是天 - Compress: true, // 是否需要压缩滚动日志, 使用的 gzip 压缩 - } - - fileHook := LumberHook{lumberLog} - - Log.AddHook(&fileHook) -} diff --git a/config/config.go b/config/config.go index 60ac7c1..4e4414b 100644 --- a/config/config.go +++ b/config/config.go @@ -6,6 +6,20 @@ import ( "time" ) +type SqliteConfig struct { + // db文件名 + FileName string +} + +type PostgreSQLConfig struct { + Host string + Port int + User string + Pwd string + Dbname string + Timezone string +} + var ( ServerName = "auth-server" // 服务名称 ServerHost string @@ -13,12 +27,20 @@ var ( DebugMode bool JwtSecret []byte //jwt密钥 JwtExpire = 3 * time.Hour //jwt过期时间 - SessionExpire = 3600 * 1 // session过期时间 1h + SessionName = "as_sid" + SessionExpire = 3600 * 1 // session过期时间 1h SessionSecret = "bGjW7xiMrxC9lmXN" - DataBaseHost string - DataBasePort int - DataBaseName string LogPath = "./log" + StorageType = "postgreSQL" // postgreSQL / sqlite + Sqlite = SqliteConfig{FileName: "auth-server.db"} + PostgreSQL = PostgreSQLConfig{ + Host: "localhost", + Port: 5432, + User: "postgres", + Pwd: "123456", + Dbname: "auth-server", + Timezone: "Asia/Shanghai", + } ) func initConfig() { @@ -26,7 +48,6 @@ func initConfig() { if serverHost := os.Getenv("SERVER_HOST"); serverHost != "" { ServerHost = serverHost } - if serverPort := os.Getenv("SERVER_PORT"); serverPort != "" { ServerPort, _ = strconv.Atoi(serverPort) } @@ -36,14 +57,8 @@ func initConfig() { if jwtSecret := os.Getenv("JWT_SECRET"); jwtSecret != "" { JwtSecret = []byte(jwtSecret) } - if dataBaseHost := os.Getenv("DATABASE_HOST"); dataBaseHost != "" { - DataBaseHost = dataBaseHost - } - if dataBasePort := os.Getenv("DATABASE_PORT"); dataBasePort != "" { - DataBasePort, _ = strconv.Atoi(dataBasePort) - } - if dataBaseName := os.Getenv("DATABASE_NAME"); dataBaseName != "" { - DataBaseName = dataBaseName + if sessionName := os.Getenv("SESSION_NAME"); sessionName != "" { + SessionName = sessionName } if sessionSecret := os.Getenv("SESSION_SECRET"); sessionSecret != "" { SessionSecret = sessionSecret @@ -51,4 +66,28 @@ func initConfig() { if logPath := os.Getenv("LOG_PATH"); logPath != "" { LogPath = logPath } + if storageType := os.Getenv("STORAGE_TYPE"); storageType != "" { + StorageType = storageType + } + if sqliteFileName := os.Getenv("SQLITE_FILE_NAME"); sqliteFileName != "" { + Sqlite.FileName = sqliteFileName + } + if postgresqlHost := os.Getenv("POSTGRESQL_HOST"); postgresqlHost != "" { + PostgreSQL.Host = postgresqlHost + } + if postgresqlPort := os.Getenv("POSTGRESQL_PORT"); postgresqlPort != "" { + PostgreSQL.Port, _ = strconv.Atoi(postgresqlPort) + } + if postgresqlUser := os.Getenv("POSTGRESQL_USER"); postgresqlUser != "" { + PostgreSQL.User = postgresqlUser + } + if postgresqlPwd := os.Getenv("POSTGRESQL_PWD"); postgresqlPwd != "" { + PostgreSQL.Pwd = postgresqlPwd + } + if postgresqlDbName := os.Getenv("POSTGRESQL_DB_NAME"); postgresqlDbName != "" { + PostgreSQL.Dbname = postgresqlDbName + } + if postgresqlTimezone := os.Getenv("POSTGRESQL_TIMEZONE"); postgresqlTimezone != "" { + PostgreSQL.Timezone = postgresqlTimezone + } } diff --git a/go.mod b/go.mod index beb834a..75cd054 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.22 toolchain go1.22.1 require ( + github.com/gin-contrib/sessions v1.0.0 github.com/gin-gonic/contrib v0.0.0-20221130124618-7e01895a63f2 github.com/gin-gonic/gin v1.9.1 github.com/golang-jwt/jwt/v5 v5.2.0 @@ -13,9 +14,11 @@ require ( github.com/spf13/viper v1.16.0 github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.0 + github.com/swaggo/swag v1.16.3 gopkg.in/natefinch/lumberjack.v2 v2.2.1 + gorm.io/driver/postgres v1.5.7 gorm.io/driver/sqlite v1.5.5 - gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde + gorm.io/gorm v1.25.8 ) require ( @@ -24,7 +27,6 @@ require ( github.com/bytedance/sonic v1.11.3 // indirect github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect github.com/chenzhuoyu/iasm v0.9.1 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect github.com/fsnotify/fsnotify v1.6.0 // indirect github.com/gabriel-vasile/mimetype v1.4.3 // indirect github.com/gin-contrib/sse v0.1.0 // indirect @@ -37,10 +39,14 @@ require ( github.com/go-playground/validator/v10 v10.19.0 // indirect github.com/goccy/go-json v0.10.2 // indirect github.com/gomodule/redigo v2.0.0+incompatible // indirect - github.com/gorilla/context v1.1.1 // indirect - github.com/gorilla/securecookie v1.1.1 // indirect - github.com/gorilla/sessions v1.2.1 // indirect + github.com/gorilla/context v1.1.2 // indirect + github.com/gorilla/securecookie v1.1.2 // indirect + github.com/gorilla/sessions v1.2.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 // indirect + github.com/jackc/pgx/v5 v5.5.5 // indirect + github.com/jackc/puddle/v2 v2.2.1 // indirect github.com/jinzhu/inflection v1.0.0 // indirect github.com/jinzhu/now v1.1.5 // indirect github.com/josharian/intern v1.0.0 // indirect @@ -54,28 +60,22 @@ require ( github.com/mitchellh/mapstructure v1.5.0 // 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.1.1 // indirect - github.com/russross/blackfriday/v2 v2.1.0 // indirect - github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect + github.com/pelletier/go-toml/v2 v2.2.1 // indirect github.com/spf13/afero v1.9.5 // indirect github.com/spf13/cast v1.5.1 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect github.com/subosito/gotenv v1.6.0 // indirect - github.com/swaggo/swag v1.16.3 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.2.12 // indirect - github.com/urfave/cli/v2 v2.27.1 // indirect - github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 // indirect golang.org/x/arch v0.7.0 // indirect - golang.org/x/crypto v0.21.0 // indirect - golang.org/x/net v0.22.0 // indirect - golang.org/x/sys v0.18.0 // indirect + golang.org/x/crypto v0.22.0 // indirect + golang.org/x/net v0.24.0 // indirect + golang.org/x/sync v0.6.0 // indirect + golang.org/x/sys v0.19.0 // indirect golang.org/x/text v0.14.0 // indirect golang.org/x/tools v0.19.0 // indirect google.golang.org/protobuf v1.33.0 // indirect gopkg.in/ini.v1 v1.67.0 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - sigs.k8s.io/yaml v1.4.0 // indirect ) diff --git a/go.sum b/go.sum index e198d7b..d3ebc51 100644 --- a/go.sum +++ b/go.sum @@ -61,8 +61,6 @@ github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDk github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= -github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4= -github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -80,6 +78,8 @@ github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uq github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= github.com/gin-contrib/gzip v0.0.6 h1:NjcunTcGAj5CO1gn4N8jHOSIeRFHIbn51z6K+xaN4d4= github.com/gin-contrib/gzip v0.0.6/go.mod h1:QOJlmV2xmayAjkNS2Y8NQsMneuRShOU/kjovCXNuzzk= +github.com/gin-contrib/sessions v1.0.0 h1:r5GLta4Oy5xo9rAwMHx8B4wLpeRGHMdz9NafzJAdP8Y= +github.com/gin-contrib/sessions v1.0.0/go.mod h1:DN0f4bvpqMQElDdi+gNGScrP2QEI04IErRyMFyorUOI= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/contrib v0.0.0-20221130124618-7e01895a63f2 h1:dyuNlYlG1faymw39NdJddnzJICy6587tiGSVioWhYoE= @@ -150,6 +150,8 @@ github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/ github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= +github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= @@ -168,19 +170,29 @@ github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+ github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= github.com/googleapis/google-cloud-go-testing v0.0.0-20200911160855-bcd43fbb19e8/go.mod h1:dvDLG8qkwmyD9a/MJJN3XJcT3xFxOKAvTZGvuZmac9g= -github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= -github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= +github.com/gorilla/context v1.1.2 h1:WRkNAv2uoa03QNIc1A6u4O7DAGMUVoopZhkiXWA2V1o= +github.com/gorilla/context v1.1.2/go.mod h1:KDPwT9i/MeWHiLl90fuTgrt4/wPcv75vFAZLaOOcbxM= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/securecookie v1.1.2 h1:YCIWL56dvtr73r6715mJs5ZvhtnY73hBvEF8kXD8ePA= +github.com/gorilla/securecookie v1.1.2/go.mod h1:NfCASbcHqRSY+3a8tlWJwsQap2VX5pwzwo4h3eOamfo= github.com/gorilla/sessions v1.1.1/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w= -github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= -github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/gorilla/sessions v1.2.2 h1:lqzMYz6bOfvn2WriPUjNByzeXIlVzURcPmgMczkmTjY= +github.com/gorilla/sessions v1.2.2/go.mod h1:ePLdVu+jbEgHH+KWw8I1z2wqd0BAdAQh/8LRvBeoNcQ= github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9 h1:L0QtFUgDarD7Fpv9jeVMgy/+Ec0mtnmYuImjTz6dtDA= +github.com/jackc/pgservicefile v0.0.0-20231201235250-de7065d80cb9/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw= +github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A= +github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= +github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= @@ -221,8 +233,10 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w 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.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= -github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pelletier/go-toml/v2 v2.2.0 h1:QLgLl2yMN7N+ruc31VynXs1vhMZa7CeHHejIeBAsoHo= +github.com/pelletier/go-toml/v2 v2.2.0/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pelletier/go-toml/v2 v2.2.1 h1:9TA9+T8+8CUCO2+WYnDLCgrYi9+omqKXyjDtosvtEhg= +github.com/pelletier/go-toml/v2 v2.2.1/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= @@ -232,10 +246,6 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1: github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= -github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= -github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= -github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/spf13/afero v1.9.5 h1:stMpOSZFs//0Lv29HduCmli3GUfpFoF3Y1Q/aXj/wVM= @@ -251,6 +261,7 @@ github.com/spf13/viper v1.16.0/go.mod h1:yg78JgCJcbrQOvV9YLXgkLaZqUidkY9K+Dd1Fof 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.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= @@ -274,10 +285,6 @@ github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= -github.com/urfave/cli/v2 v2.27.1 h1:8xSQ6szndafKVRmfyeUMxkNUJQMjL1F2zmsZ+qHpfho= -github.com/urfave/cli/v2 v2.27.1/go.mod h1:8qnjx1vcq5s2/wpsqoZFndg2CE5tNFyrTvS6SinrnYQ= -github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913 h1:+qGGcbkzsfDQNPPe9UDgpxAWQrhbbBXOYJFQDq/dtJw= -github.com/xrash/smetrics v0.0.0-20240312152122-5f08fbb34913/go.mod h1:4aEEwZQutDLsQv2Deui4iYQ6DWTxR14g6m8Wv88+Xqk= github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= @@ -302,6 +309,8 @@ golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5y golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= @@ -374,6 +383,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc= golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= +golang.org/x/net v0.24.0 h1:1PcaxkF854Fu3+lvBIx5SYn9wRlBzzcnHZSiaFFAb0w= +golang.org/x/net v0.24.0/go.mod h1:2Q7sJY5mzlzWjKtYUEXSlBWCdyaioyXzRB2RtU8KVE8= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= @@ -394,6 +405,8 @@ golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ= +golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -437,6 +450,8 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= +golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -608,15 +623,15 @@ gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc= gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc= gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= 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= +gorm.io/driver/postgres v1.5.7 h1:8ptbNJTDbEmhdr62uReG5BGkdQyeasu/FZHxI0IMGnM= +gorm.io/driver/postgres v1.5.7/go.mod h1:3e019WlBaYI5o5LIdNV+LyxCMNtLOQETBXL2h4chKpA= gorm.io/driver/sqlite v1.5.5 h1:7MDMtUZhV065SilG62E0MquljeArQZNfJnjd9i9gx3E= gorm.io/driver/sqlite v1.5.5/go.mod h1:6NgQ7sQWAIFsPrJJl1lSNSu2TABh0ZZ/zm5fosATavE= -gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde h1:9DShaph9qhkIYw7QF91I/ynrr4cOO2PZra2PFD7Mfeg= -gorm.io/gorm v1.25.7-0.20240204074919-46816ad31dde/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= +gorm.io/gorm v1.25.8 h1:WAGEZ/aEcznN4D03laj8DKnehe1e9gYQAjW8xyPRdeo= +gorm.io/gorm v1.25.8/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= @@ -629,5 +644,3 @@ rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8 rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= -sigs.k8s.io/yaml v1.4.0 h1:Mk1wCc2gy/F0THH0TAp1QYyJNzRm2KCLy3o5ASXVI5E= -sigs.k8s.io/yaml v1.4.0/go.mod h1:Ejl7/uTz7PSA4eKMyQCUTnhZYNmLIl+5c2lQPGR2BPY= diff --git a/loader/engine.go b/loader/engine.go new file mode 100644 index 0000000..30615b2 --- /dev/null +++ b/loader/engine.go @@ -0,0 +1,40 @@ +package loader + +import ( + "auth-server/config" + "auth-server/middleware" + "auth-server/router" + + "github.com/gin-contrib/sessions" + "github.com/gin-gonic/gin" + swaggerFiles "github.com/swaggo/files" + ginSwagger "github.com/swaggo/gin-swagger" +) + +func InitEngine() *gin.Engine { + // 是否开启debug模式 + if !config.DebugMode { + gin.SetMode(gin.ReleaseMode) + } + + engine := gin.New() + engine.Use(gin.Recovery()) + + // session设置 + sessionRedisStore := initSessionRedis() + engine.Use(sessions.Sessions(config.SessionName, sessionRedisStore)) + + // 日志设置 + engine.Use(middleware.LogMiddleware()) + + // 初始化引擎路由 + engine = router.InitRouter(engine) + + // debug模式,开启swagger ui + if config.DebugMode { + engine.GET("/swagger/auth/*any", ginSwagger.WrapHandler(swaggerFiles.NewHandler(), ginSwagger.InstanceName("auth"))) + engine.GET("/swagger/v1/*any", ginSwagger.WrapHandler(swaggerFiles.NewHandler(), ginSwagger.InstanceName("v1"))) + } + + return engine +} diff --git a/loader/log.go b/loader/log.go new file mode 100644 index 0000000..11ac0b9 --- /dev/null +++ b/loader/log.go @@ -0,0 +1,28 @@ +package loader + +import ( + "auth-server/common" + "path" + + "gopkg.in/natefinch/lumberjack.v2" +) + +func InitLog(logPath, appName string) { + + // 设置日志输出格式 + common.Log.SetFormatter(&common.MyFormatter{}) + + logFileName := path.Join(logPath, appName) + // 使用滚动压缩方式记录日志 + lumberLog := &lumberjack.Logger{ + Filename: logFileName, //日志文件位置 + MaxSize: 1, // 单文件最大容量,单位是MB + MaxBackups: 3, // 最大保留过期文件个数 + MaxAge: 1, // 保留过期文件的最大时间间隔,单位是天 + Compress: true, // 是否需要压缩滚动日志, 使用的 gzip 压缩 + } + + fileHook := common.LumberHook{Logger: lumberLog} + + common.Log.AddHook(&fileHook) +} diff --git a/loader/session-redis.go b/loader/session-redis.go new file mode 100644 index 0000000..181b819 --- /dev/null +++ b/loader/session-redis.go @@ -0,0 +1,18 @@ +package loader + +import ( + "auth-server/config" + + "github.com/gin-contrib/sessions" + "github.com/gin-contrib/sessions/redis" +) + +func initSessionRedis() sessions.Store { + store, _ := redis.NewStore(10, "tcp", "localhost:6379", "", []byte("secret")) + store.Options(sessions.Options{ + Path: "/", + MaxAge: config.SessionExpire, + }) + + return store +} diff --git a/main.go b/main.go index 028eabf..7054568 100644 --- a/main.go +++ b/main.go @@ -1,13 +1,23 @@ package main import ( - "auth-server/common" "auth-server/config" - "auth-server/router" + "auth-server/loader" + "strconv" + + log "github.com/sirupsen/logrus" ) func main() { - //初始化日志 - common.InitLog(config.LogPath, config.ServerName) - router.InitRouter() + loader.InitLog(config.LogPath, config.ServerName) + + engine := loader.InitEngine() + + port := config.ServerPort + runParams := config.ServerHost + ":" + strconv.Itoa(port) + log.Println("master server at ", runParams) + if err := engine.Run(runParams); err != nil { + log.Error(err) + return + } } diff --git a/middleware/sess.go b/middleware/sess.go index 72ff5b4..55f65d9 100644 --- a/middleware/sess.go +++ b/middleware/sess.go @@ -2,7 +2,7 @@ package middleware import ( "auth-server/model" - "github.com/gin-gonic/contrib/sessions" + "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" ) diff --git a/middleware/validator.go b/middleware/validator.go deleted file mode 100644 index 2e2aa41..0000000 --- a/middleware/validator.go +++ /dev/null @@ -1,29 +0,0 @@ -package middleware - -import ( - "auth-server/model" - - "github.com/gin-gonic/gin" - "github.com/gin-gonic/gin/binding" -) - -func Validate[P, Q, B any](c *gin.Context) (params P, query Q, body B) { - if err := c.ShouldBindUri(¶ms); err != nil { - Fail(c, model.ErrParam.AddErr(err)) - return - } - - if err := c.ShouldBindWith(&query, binding.Query); err != nil { - Fail(c, model.ErrParam.AddErr(err)) - return - } - - if c.Request.ContentLength != 0 { - if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil { - Fail(c, model.ErrParam.AddErr(err)) - return - } - } - - return -} diff --git a/model/user.go b/model/user.go index 234dd26..a8935f5 100644 --- a/model/user.go +++ b/model/user.go @@ -18,8 +18,10 @@ type UpdateUser struct { // LoginUser 用户登陆参数校验 type LoginUser struct { - Username string `json:"username" binding:"required"` - Password string `json:"password" binding:"required"` + // 用户名 + Username string `json:"username" binding:"required" example:"user"` + // 用户密码 + Password string `json:"password" binding:"required" example:"pass"` } type GetUserParams struct { diff --git a/router/auth.go b/router/auth.go index 8669c62..4fb29d8 100644 --- a/router/auth.go +++ b/router/auth.go @@ -1,9 +1,14 @@ package router -import "github.com/gin-gonic/gin" +import ( + "github.com/gin-gonic/gin" +) -func authRouter(router *gin.RouterGroup) { - router.POST("/login", apiAuth.Login) - router.POST("/register", apiAuth.Register) - router.POST("/logout", apiAuth.Logout) +// @title 本地身份认证接口 +// @BasePath /auth + +func AuthRegister(g *gin.RouterGroup) { + g.POST("/login", authApis.Login) + g.POST("/register", authApis.Register) + g.POST("/logout", authApis.Logout) } diff --git a/router/init.go b/router/init.go index a3c931f..f5153f5 100644 --- a/router/init.go +++ b/router/init.go @@ -1,71 +1,27 @@ package router import ( - "auth-server/api" - "auth-server/config" - "auth-server/docs" - "auth-server/middleware" - "strconv" + "auth-server/api/auth" + v1 "auth-server/api/v1" - swaggerFiles "github.com/swaggo/files" - ginSwagger "github.com/swaggo/gin-swagger" - - "github.com/gin-gonic/contrib/sessions" + _ "auth-server/docs" "github.com/gin-gonic/gin" - log "github.com/sirupsen/logrus" ) var ( - apiAuth api.AuthApi - apiUser api.UserApi + authApis auth.Apis + userApis v1.UserApi ) -var ( - authRoutesPrefix = "/auth" - serviceRoutesPrefix = "/api/v1" -) - -var sessionName = "sid" - -func InitRouter() { - //是否开启debug模式 - if !config.DebugMode { - gin.SetMode(gin.ReleaseMode) - } - - engine := gin.New() - engine.Use(gin.Recovery()) - - if config.DebugMode { - engine.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) - docs.SwaggerInfo.BasePath = authRoutesPrefix - } - - // session 设置 - store := sessions.NewCookieStore([]byte(config.SessionSecret)) - store.Options(sessions.Options{ - Path: "/", - MaxAge: config.SessionExpire, // 设置超时时间为一个小时 - }) - engine.Use(sessions.Sessions(sessionName, store)) - - // 日志设置 - engine.Use(middleware.LogMiddleware()) +func InitRouter(engine *gin.Engine) *gin.Engine { + // auth路由组 + authGroup := engine.Group("/auth") + AuthRegister(authGroup) - // 登陆认证相关路由 - authRouterGroup := engine.Group(authRoutesPrefix) - authRouter(authRouterGroup) - // 业务路由 - serviceRouterGroup := engine.Group(serviceRoutesPrefix) - serviceRouterGroup.Use(middleware.SessionAuth()) - userRouter(serviceRouterGroup) + // v1业务路由组 + v1Group := engine.Group("/api/v1") + V1Register(v1Group) - port := config.ServerPort - runParams := config.ServerHost + ":" + strconv.Itoa(port) - log.Println("master server at ", runParams) - if err := engine.Run(runParams); err != nil { - log.Error(err) - return - } + return engine } diff --git a/router/user.go b/router/user.go deleted file mode 100644 index a6442c6..0000000 --- a/router/user.go +++ /dev/null @@ -1,12 +0,0 @@ -package router - -import ( - "github.com/gin-gonic/gin" -) - -func userRouter(router *gin.RouterGroup) { - // user - router.GET("/users/:id", apiUser.GetUser) - router.PATCH("/users/:id", apiUser.UpdateUser) - router.DELETE("/users/:id", apiUser.DeleteUser) -} diff --git a/router/v1.go b/router/v1.go new file mode 100644 index 0000000..31f9b33 --- /dev/null +++ b/router/v1.go @@ -0,0 +1,13 @@ +package router + +import ( + "github.com/gin-gonic/gin" +) + +// @title 业务逻辑接口 +// @version 1.0 +// @BasePath /api/v1 + +func V1Register(g *gin.RouterGroup) { + g.GET("/users/:id", userApis.GetUser) +} diff --git a/services/auth.go b/services/auth.go index 8fdcfbd..b6edc49 100644 --- a/services/auth.go +++ b/services/auth.go @@ -3,7 +3,7 @@ package services import ( "auth-server/common" "auth-server/model" - "github.com/gin-gonic/contrib/sessions" + "github.com/gin-contrib/sessions" "github.com/gin-gonic/gin" "github.com/pkg/errors" ) diff --git a/storage/init.go b/storage/init.go index 69af0de..bbafe7a 100644 --- a/storage/init.go +++ b/storage/init.go @@ -1,32 +1,36 @@ package storage import ( + "auth-server/config" "auth-server/model" + "fmt" log "github.com/sirupsen/logrus" + "gorm.io/driver/postgres" "gorm.io/driver/sqlite" "gorm.io/gorm" ) var ( - dbFileName = "auth-server.db" - db *gorm.DB + db *gorm.DB + postgresDsn = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s Timezone=%s", config.PostgreSQL.Host, config.PostgreSQL.Port, config.PostgreSQL.User, config.PostgreSQL.Pwd, config.PostgreSQL.Dbname, config.PostgreSQL.Timezone) + sqliteFileName = config.Sqlite.FileName ) +type EngineStorage struct{} + func init() { err := initStorageEngine() if err != nil { - log.Fatalf("init storage Engine error: %s", err) + log.Fatalf("init storage Engine error: %s", err.Error()) } } -type EngineStorage struct{} - -func (EngineStorage) GetStorageDB() *gorm.DB { - return db -} - func initStorageEngine() (err error) { - db, err = gorm.Open(sqlite.Open(dbFileName), &gorm.Config{}) + if config.StorageType == "postgreSQL" { + db, err = gorm.Open(postgres.Open(postgresDsn), &gorm.Config{}) + } else if config.StorageType == "sqlite" { + db, err = gorm.Open(sqlite.Open(sqliteFileName), &gorm.Config{}) + } if err != nil { return } @@ -36,3 +40,7 @@ func initStorageEngine() (err error) { } return } + +func (EngineStorage) GetStorageDB() *gorm.DB { + return db +}