Skip to content

Commit

Permalink
Merge pull request #11 from OTOT-dev/change-db
Browse files Browse the repository at this point in the history
Change db
  • Loading branch information
xudaqian1 authored Apr 25, 2024
2 parents c44891e + 2ec2681 commit d52341d
Show file tree
Hide file tree
Showing 25 changed files with 315 additions and 235 deletions.
6 changes: 1 addition & 5 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
.idea
.vscode

*.db

tmp
Expand Down
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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://<BaseUrl>/swagger/index.html查看。



## 参考
Expand Down
20 changes: 13 additions & 7 deletions api/auth.go → api/auth/auth.go
Original file line number Diff line number Diff line change
@@ -1,36 +1,42 @@
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(&param); err != nil {
middleware.Fail(c, model.ErrParam.AddErr(err))
return
}
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(&param); err != nil {
middleware.Fail(c, model.ErrParam.AddErr(err))
return
}
err := authService.Register(&param)
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)
}
5 changes: 5 additions & 0 deletions api/auth/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package auth

import "auth-server/services"

var authService services.AuthService
10 changes: 0 additions & 10 deletions api/init.go

This file was deleted.

5 changes: 5 additions & 0 deletions api/v1/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package v1

import "auth-server/services"

var userService services.UserService
26 changes: 13 additions & 13 deletions api/user.go → api/v1/user.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package api
package v1

import (
"auth-server/middleware"
Expand All @@ -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(&params); err != nil {
middleware.Fail(c, model.ErrParam.AddErr(err))
return
}

userId, err := strconv.ParseInt(params.Id, 10, 64)
if err != nil {
Expand All @@ -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) {
Expand Down
26 changes: 3 additions & 23 deletions common/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}

Expand All @@ -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)
}
65 changes: 52 additions & 13 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,48 @@ 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
ServerPort int
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() {
//环境变量生效优先级 命令行》环境变量》配置文件
if serverHost := os.Getenv("SERVER_HOST"); serverHost != "" {
ServerHost = serverHost
}

if serverPort := os.Getenv("SERVER_PORT"); serverPort != "" {
ServerPort, _ = strconv.Atoi(serverPort)
}
Expand All @@ -36,19 +57,37 @@ 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
}
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
}
}
32 changes: 16 additions & 16 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 (
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
)
Loading

0 comments on commit d52341d

Please sign in to comment.