Skip to content

Commit c1049de

Browse files
committed
token
1 parent b21eae8 commit c1049de

File tree

22 files changed

+697
-43
lines changed

22 files changed

+697
-43
lines changed

api/controller/user/user.go

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ package user
33
import (
44
"github.com/gin-gonic/gin"
55
"wow-admin/api/router"
6-
"wow-admin/model/dto"
6+
"wow-admin/model/req"
77
"wow-admin/service"
88
"wow-admin/utils"
99
"wow-admin/utils/result"
@@ -25,26 +25,26 @@ func init() {
2525

2626
// 后台登录
2727
func (c *UserController) login(ctx *gin.Context) {
28-
loginReq := utils.BindValidJson[dto.Login](ctx)
28+
loginReq := utils.BindValidJson[req.Login](ctx)
2929

3030
loginVO, code := c.userService.Login(ctx, loginReq.Username, loginReq.Password)
3131

3232
result.SendData(ctx, code, loginVO)
3333
}
3434

35+
// 注册
3536
func (c *UserController) register(ctx *gin.Context) {
36-
registerReq := utils.BindValidJson[dto.Register](ctx)
37-
code := c.userService.Register(registerReq)
38-
result.SendCode(ctx, code)
37+
// data := utils.BindValidJson[dto.Register](ctx)
38+
// validMsg := utils.Validate(ctx, &data)
39+
// if validMsg != "" {
40+
// result.ReturnJSON(ctx, http.StatusOK, result.ERROR_INVALID_PARAM, validMsg, nil)
41+
// return
42+
// }
43+
// result.SendCode(ctx, c.userService.Register(data))
44+
45+
result.SendCode(ctx, c.userService.Register(utils.BindValidJson[req.Register](ctx)))
3946
}
4047

4148
func (c *UserController) getUserInfo(ctx *gin.Context) {
42-
username := "Test"
43-
password := "123"
44-
45-
user := make(map[string]string)
46-
user["username"] = username
47-
user["password"] = password
48-
49-
result.SendData(ctx, 0, user)
49+
result.SuccessData(ctx, c.userService.GetUserInfo(utils.GetFromContext[int](ctx, "userId")))
5050
}

api/middleware/auth.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ package middleware
33
import (
44
"github.com/gin-gonic/gin"
55
"strings"
6-
"time"
76
"wow-admin/utils"
87
"wow-admin/utils/result"
98
)
@@ -48,15 +47,15 @@ func AuthLogin() gin.HandlerFunc {
4847
}
4948

5049
// 判断 token 已过期
51-
if time.Now().Unix() > claims.ExpiresAt.Unix() {
52-
result.SendCode(c, result.ERROR_TOKEN_RUNTIME)
53-
c.Abort()
54-
return
55-
}
50+
//if time.Now().Unix() > claims.ExpiresAt.Unix() {
51+
// result.SendCode(c, result.ERROR_TOKEN_RUNTIME)
52+
// c.Abort()
53+
// return
54+
//}
5655

5756
// 将当前请求的相关信息保存到请求的上下文 c 上
5857
// 后续的处理函数可以用过 c.Get("xxx") 来获取当前请求的用户信息
59-
c.Set("user_info_id", claims.UserId)
58+
c.Set("userId", claims.UserId)
6059
c.Set("role", claims.Role)
6160
c.Set("uuid", claims.UUID)
6261

api/middleware/error.go

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package middleware
2+
3+
import (
4+
"github.com/gin-gonic/gin"
5+
"go.uber.org/zap"
6+
"net"
7+
"net/http"
8+
"net/http/httputil"
9+
"os"
10+
"runtime/debug"
11+
"strings"
12+
"wow-admin/utils"
13+
"wow-admin/utils/result"
14+
)
15+
16+
// recover 项目可能出现的 panic, 并使用 zap 记录相关日志
17+
func ErrorRecovery(stack bool) gin.HandlerFunc {
18+
return func(ctx *gin.Context) {
19+
defer func() {
20+
if err := recover(); err != nil && err != "wow oh no!" {
21+
// Check for a broken connection, as it is not really a
22+
// condition that warrants a panic stack trace.
23+
var brokenPipe bool
24+
if ne, ok := err.(*net.OpError); ok {
25+
if se, ok := ne.Err.(*os.SyscallError); ok {
26+
if strings.Contains(strings.ToLower(se.Error()), "broken pipe") || strings.Contains(strings.ToLower(se.Error()), "connection reset by peer") {
27+
brokenPipe = true
28+
}
29+
}
30+
}
31+
32+
// 处理 panic(xxx) 的操作
33+
// err 类型断言
34+
if code, ok := err.(int); ok { // panic(code) 根据错误码获取 msg
35+
result.SendCode(ctx, code)
36+
} else if msg, ok := err.(string); ok { // panic(string) 返回 string
37+
result.ReturnJSON(ctx, http.StatusOK, result.FAIL, msg, nil)
38+
} else if e, ok := err.(error); ok { // panic(error) 发送消息
39+
result.ReturnJSON(ctx, http.StatusOK, result.FAIL, e.Error(), nil)
40+
} else { // 其他
41+
result.Send(ctx, http.StatusOK, result.FAIL, nil)
42+
}
43+
44+
httpRequest, _ := httputil.DumpRequest(ctx.Request, false)
45+
if brokenPipe {
46+
utils.Logger.Error(ctx.Request.URL.Path,
47+
zap.Any("error", err),
48+
zap.String("request", string(httpRequest)),
49+
)
50+
// If the connection is dead, we can't write a status to it.
51+
_ = ctx.Error(err.(error)) // nolint: err check
52+
ctx.Abort()
53+
return
54+
}
55+
56+
if stack {
57+
utils.Logger.Error("[Recovery from panic]",
58+
zap.Any("error", err),
59+
zap.String("request", string(httpRequest)),
60+
zap.String("stack", string(debug.Stack())),
61+
)
62+
} else {
63+
utils.Logger.Error("[Recovery from panic]",
64+
zap.Any("error", err),
65+
zap.String("request", string(httpRequest)),
66+
)
67+
}
68+
ctx.AbortWithStatus(http.StatusInternalServerError)
69+
}
70+
}()
71+
ctx.Next()
72+
}
73+
}

api/middleware/gin_logger.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ func RouterLogger() gin.HandlerFunc {
1616
utils.Logger.Info(c.Request.URL.Path,
1717
zap.Int("status", c.Writer.Status()),
1818
zap.String("method", c.Request.Method),
19-
// zap.String("path", c.Request.URL.Path),
19+
zap.String("path", c.Request.URL.Path),
2020
zap.String("query", c.Request.URL.RawQuery),
2121
zap.String("ip", c.ClientIP()),
2222
zap.String("user-agent", c.Request.UserAgent()),

api/router/router.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,9 @@ var _defaultWebServer WebServer
4646
var _defaultWebRouter = gin.New()
4747

4848
func init() {
49-
_defaultWebRouter.Use(middleware.RouterLogger(), gin.Recovery())
49+
// _defaultWebRouter.Use(middleware.RouterLogger(), gin.Recovery())
50+
_defaultWebRouter.Use(middleware.RouterLogger())
51+
_defaultWebRouter.Use(middleware.ErrorRecovery(false)) // 自定义错误处理中间件,不使用gin.Recovery()
5052
_defaultWebRouter.Use(middleware.Cors())
5153
_defaultWebRouter.Use(middleware.AuthLogin())
5254
}

assets/ip2region.xdb

10.6 MB
Binary file not shown.

assets/wait-for

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
#!/bin/sh
2+
3+
# The MIT License (MIT)
4+
#
5+
# Copyright (c) 2017 Eficode Oy
6+
#
7+
# Permission is hereby granted, free of charge, to any person obtaining a copy
8+
# of this software and associated documentation files (the "Software"), to deal
9+
# in the Software without restriction, including without limitation the rights
10+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11+
# copies of the Software, and to permit persons to whom the Software is
12+
# furnished to do so, subject to the following conditions:
13+
#
14+
# The above copyright notice and this permission notice shall be included in all
15+
# copies or substantial portions of the Software.
16+
#
17+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23+
# SOFTWARE.
24+
25+
VERSION="2.2.3"
26+
27+
set -- "$@" -- "$TIMEOUT" "$QUIET" "$PROTOCOL" "$HOST" "$PORT" "$result"
28+
TIMEOUT=15
29+
QUIET=0
30+
# The protocol to make the request with, either "tcp" or "http"
31+
PROTOCOL="tcp"
32+
33+
echoerr() {
34+
if [ "$QUIET" -ne 1 ]; then printf "%s\n" "$*" 1>&2; fi
35+
}
36+
37+
usage() {
38+
exitcode="$1"
39+
cat << USAGE >&2
40+
Usage:
41+
$0 host:port|url [-t timeout] [-- command args]
42+
-q | --quiet Do not output any status messages
43+
-t TIMEOUT | --timeout=timeout Timeout in seconds, zero for no timeout
44+
-v | --version Show the version of this tool
45+
-- COMMAND ARGS Execute command with args after the test finishes
46+
USAGE
47+
exit "$exitcode"
48+
}
49+
50+
wait_for() {
51+
case "$PROTOCOL" in
52+
tcp)
53+
if ! command -v nc >/dev/null; then
54+
echoerr 'nc command is missing!'
55+
exit 1
56+
fi
57+
;;
58+
http)
59+
if ! command -v wget >/dev/null; then
60+
echoerr 'wget command is missing!'
61+
exit 1
62+
fi
63+
;;
64+
esac
65+
66+
TIMEOUT_END=$(($(date +%s) + TIMEOUT))
67+
68+
while :; do
69+
case "$PROTOCOL" in
70+
tcp)
71+
nc -w 1 -z "$HOST" "$PORT" > /dev/null 2>&1
72+
;;
73+
http)
74+
wget --timeout=1 -q "$HOST" -O /dev/null > /dev/null 2>&1
75+
;;
76+
*)
77+
echoerr "Unknown protocol '$PROTOCOL'"
78+
exit 1
79+
;;
80+
esac
81+
82+
result=$?
83+
84+
if [ $result -eq 0 ] ; then
85+
if [ $# -gt 7 ] ; then
86+
for result in $(seq $(($# - 7))); do
87+
result=$1
88+
shift
89+
set -- "$@" "$result"
90+
done
91+
92+
TIMEOUT=$2 QUIET=$3 PROTOCOL=$4 HOST=$5 PORT=$6 result=$7
93+
shift 7
94+
exec "$@"
95+
fi
96+
exit 0
97+
fi
98+
99+
if [ $TIMEOUT -ne 0 -a $(date +%s) -ge $TIMEOUT_END ]; then
100+
echo "Operation timed out" >&2
101+
exit 1
102+
fi
103+
104+
sleep 1
105+
done
106+
}
107+
108+
while :; do
109+
case "$1" in
110+
http://*|https://*)
111+
HOST="$1"
112+
PROTOCOL="http"
113+
shift 1
114+
;;
115+
*:* )
116+
HOST=$(printf "%s\n" "$1"| cut -d : -f 1)
117+
PORT=$(printf "%s\n" "$1"| cut -d : -f 2)
118+
shift 1
119+
;;
120+
-v | --version)
121+
echo $VERSION
122+
exit
123+
;;
124+
-q | --quiet)
125+
QUIET=1
126+
shift 1
127+
;;
128+
-q-*)
129+
QUIET=0
130+
echoerr "Unknown option: $1"
131+
usage 1
132+
;;
133+
-q*)
134+
QUIET=1
135+
result=$1
136+
shift 1
137+
set -- -"${result#-q}" "$@"
138+
;;
139+
-t | --timeout)
140+
TIMEOUT="$2"
141+
shift 2
142+
;;
143+
-t*)
144+
TIMEOUT="${1#-t}"
145+
shift 1
146+
;;
147+
--timeout=*)
148+
TIMEOUT="${1#*=}"
149+
shift 1
150+
;;
151+
--)
152+
shift
153+
break
154+
;;
155+
--help)
156+
usage 0
157+
;;
158+
-*)
159+
QUIET=0
160+
echoerr "Unknown option: $1"
161+
usage 1
162+
;;
163+
*)
164+
QUIET=0
165+
echoerr "Unknown argument: $1"
166+
usage 1
167+
;;
168+
esac
169+
done
170+
171+
if ! [ "$TIMEOUT" -ge 0 ] 2>/dev/null; then
172+
echoerr "Error: invalid timeout '$TIMEOUT'"
173+
usage 3
174+
fi
175+
176+
case "$PROTOCOL" in
177+
tcp)
178+
if [ "$HOST" = "" ] || [ "$PORT" = "" ]; then
179+
echoerr "Error: you need to provide a host and port to test."
180+
usage 2
181+
fi
182+
;;
183+
http)
184+
if [ "$HOST" = "" ]; then
185+
echoerr "Error: you need to provide a host to test."
186+
usage 2
187+
fi
188+
;;
189+
esac
190+
191+
wait_for "$@"

config/config.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ Mysql:
2020
LogMode: info # silent 相当于关闭日志
2121

2222
Redis:
23-
DB: 7
23+
DB: 11
2424
Addr: 127.0.0.1:6379
2525
Password: ""
2626
Session:

0 commit comments

Comments
 (0)