-
Notifications
You must be signed in to change notification settings - Fork 0
/
admin.go
95 lines (90 loc) · 2.08 KB
/
admin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"errors"
"github.com/labstack/echo/v4"
"goproxy2/assets"
"html/template"
"io"
"log"
"net/http"
"strings"
)
type AdminTemplate struct {
templates *template.Template
}
func (t *AdminTemplate) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func parseGlob(prefix string) (*template.Template, error) {
var t *template.Template
for _, name := range assets.AssetNames() {
if strings.HasPrefix(name, prefix) {
content, err := assets.Asset(name)
if err != nil {
return nil, err
}
var tmpl *template.Template
if t == nil {
t = template.New(name)
}
if name == t.Name() {
tmpl = t
} else {
tmpl = t.New(name)
}
_, err = tmpl.Parse(string(content))
if err != nil {
return nil, err
}
}
}
return t, nil
}
func startAdmin() {
Init()
e := echo.New()
e.HTTPErrorHandler = func(err error, ctx echo.Context) {
if err != nil {
ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
"code": 500,
"msg": "请求失败" + err.Error(),
})
}
}
e.Renderer = &AdminTemplate{
templates: template.Must(parseGlob("resources/views/")),
}
e.POST("/admin/add-ip", func(ctx echo.Context) error {
remoteIp := ctx.FormValue("from")
proxyIp := ctx.FormValue("to")
if remoteIp == "" {
remoteIp = GetIpFromRemoteAddr(ctx.Request().RemoteAddr)
}
if proxyIp == "" {
return errors.New("proxyIp must not be empty")
}
AddIp(remoteIp, proxyIp)
return ctx.JSON(http.StatusOK, map[string]interface{}{
"code": 0,
})
})
e.POST("/admin/delete-ip", func(ctx echo.Context) error {
remoteIp := ctx.FormValue("from")
if remoteIp == "" {
remoteIp = GetIpFromRemoteAddr(ctx.Request().RemoteAddr)
}
DeleteIp(remoteIp)
return ctx.JSON(http.StatusOK, map[string]interface{}{
"code": 0,
})
})
e.GET("/", func(ctx echo.Context) error {
return ctx.Render(http.StatusOK, "admin/index", map[string]interface{}{
"items": ipDb,
})
})
err := e.Start(":8080")
if err != nil {
log.Println("listen :8080 failed", err)
}
}