优化代码

This commit is contained in:
GoEdgeLab
2023-08-08 14:17:16 +08:00
parent 9f24a6b3ee
commit 1f39947a89
58 changed files with 159 additions and 125 deletions

View File

@@ -161,7 +161,7 @@ func main() {
if progress >= 0 { if progress >= 0 {
if progress == 0 || progress == 1 || progress-lastProgress >= 0.1 { if progress == 0 || progress == 1 || progress-lastProgress >= 0.1 {
lastProgress = progress lastProgress = progress
log.Println(fmt.Sprintf("%.2f%%", manager.Progress()*100)) log.Printf("%.2f%%", manager.Progress()*100)
} }
} }
} else { } else {

View File

@@ -19,7 +19,6 @@ func TestAES128CFBMethod_Encrypt(t *testing.T) {
dst = dst[:len(src)] dst = dst[:len(src)]
t.Log("dst:", string(dst)) t.Log("dst:", string(dst))
src = make([]byte, len(src))
src, err = method.Decrypt(dst) src, err = method.Decrypt(dst)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@@ -64,7 +63,6 @@ func TestAES128CFBMethod_Encrypt2(t *testing.T) {
for _, dst := range sources { for _, dst := range sources {
dst2 := append([]byte{}, dst...) dst2 := append([]byte{}, dst...)
src2 := make([]byte, len(dst2))
src2, err := method.Decrypt(dst2) src2, err := method.Decrypt(dst2)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@@ -5,22 +5,22 @@ import "sync"
var eventsMap = map[string][]func(){} // event => []callbacks var eventsMap = map[string][]func(){} // event => []callbacks
var locker = sync.Mutex{} var locker = sync.Mutex{}
// 增加事件回调 // On 增加事件回调
func On(event string, callback func()) { func On(event string, callback func()) {
locker.Lock() locker.Lock()
defer locker.Unlock() defer locker.Unlock()
callbacks, _ := eventsMap[event] var callbacks = eventsMap[event]
callbacks = append(callbacks, callback) callbacks = append(callbacks, callback)
eventsMap[event] = callbacks eventsMap[event] = callbacks
} }
// 通知事件 // Notify 通知事件
func Notify(event string) { func Notify(event string) {
locker.Lock() locker.Lock()
callbacks, _ := eventsMap[event] var callbacks = eventsMap[event]
locker.Unlock() locker.Unlock()
for _, callback := range callbacks { for _, callback := range callbacks {
callback() callback()
} }

View File

@@ -65,7 +65,7 @@ func (this *AdminNode) Run() {
this.addPortsToFirewall() this.addPortsToFirewall()
// 监听信号 // 监听信号
sigQueue := make(chan os.Signal) var sigQueue = make(chan os.Signal, 8)
signal.Notify(sigQueue, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGQUIT) signal.Notify(sigQueue, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL, syscall.SIGQUIT)
go func() { go func() {
for range sigQueue { for range sigQueue {
@@ -106,8 +106,7 @@ func (this *AdminNode) Run() {
// Daemon 实现守护进程 // Daemon 实现守护进程
func (this *AdminNode) Daemon() { func (this *AdminNode) Daemon() {
var sock = gosock.NewTmpSock(teaconst.ProcessName) var sock = gosock.NewTmpSock(teaconst.ProcessName)
isDebug := lists.ContainsString(os.Args, "debug") var isDebug = lists.ContainsString(os.Args, "debug")
isDebug = true
for { for {
conn, err := sock.Dial() conn, err := sock.Dial()
if err != nil { if err != nil {

View File

@@ -26,8 +26,5 @@ func IsNewInstalled() bool {
return false return false
} }
_, err = os.Stat(homeDir + "/." + teaconst.ProcessName + "/api.yaml") _, err = os.Stat(homeDir + "/." + teaconst.ProcessName + "/api.yaml")
if err != nil { return err != nil
return true
}
return false
} }

View File

@@ -10,8 +10,10 @@ var DefaultCache = NewCache()
// TTL缓存 // TTL缓存
// 最大的缓存时间为30 * 86400 // 最大的缓存时间为30 * 86400
// Piece数据结构 // Piece数据结构
// Piece1 | Piece2 | Piece3 | ... //
// [ Item1, Item2, ... | ... // Piece1 | Piece2 | Piece3 | ...
// [ Item1, Item2, ... | ...
//
// KeyMap列表数据结构 // KeyMap列表数据结构
// { timestamp1 => [key1, key2, ...] }, ... // { timestamp1 => [key1, key2, ...] }, ...
type Cache struct { type Cache struct {
@@ -109,19 +111,11 @@ func (this *Cache) Read(key string) (item *Item) {
return this.pieces[uint64Key%this.countPieces].Read(uint64Key) return this.pieces[uint64Key%this.countPieces].Read(uint64Key)
} }
func (this *Cache) readIntKey(key uint64) (value *Item) {
return this.pieces[key%this.countPieces].Read(key)
}
func (this *Cache) Delete(key string) { func (this *Cache) Delete(key string) {
uint64Key := HashKey([]byte(key)) uint64Key := HashKey([]byte(key))
this.pieces[uint64Key%this.countPieces].Delete(uint64Key) this.pieces[uint64Key%this.countPieces].Delete(uint64Key)
} }
func (this *Cache) deleteIntKey(key uint64) {
this.pieces[key%this.countPieces].Delete(key)
}
func (this *Cache) Count() (count int) { func (this *Cache) Count() (count int) {
for _, piece := range this.pieces { for _, piece := range this.pieces {
count += piece.Count() count += piece.Count()

View File

@@ -39,7 +39,7 @@ func (this *ServiceManager) setup() {
this.onceLocker.Do(func() { this.onceLocker.Do(func() {
logFile := files.NewFile(Tea.Root + "/logs/service.log") logFile := files.NewFile(Tea.Root + "/logs/service.log")
if logFile.Exists() { if logFile.Exists() {
logFile.Delete() _ = logFile.Delete()
} }
//logger //logger

View File

@@ -107,13 +107,13 @@ func MatchPath(action *actions.ActionObject, path string) bool {
// FindParentAction 查找父级Action // FindParentAction 查找父级Action
func FindParentAction(actionPtr actions.ActionWrapper) *ParentAction { func FindParentAction(actionPtr actions.ActionWrapper) *ParentAction {
parentActionValue := reflect.ValueOf(actionPtr).Elem().FieldByName("ParentAction") action, ok := actionPtr.(interface{
if parentActionValue.IsValid() { Parent() *ParentAction
parentAction, isOk := parentActionValue.Interface().(ParentAction) })
if isOk { if ok {
return &parentAction return action.Parent()
}
} }
return nil return nil
} }
@@ -159,7 +159,7 @@ func parseAPIErr(action actions.ActionWrapper, err error) (apiNodeIsStarting boo
} }
var isRPCConnError bool var isRPCConnError bool
err, isRPCConnError = rpcerrors.HumanError(err, apiEndpoints, Tea.ConfigFile("api.yaml")) _, isRPCConnError = rpcerrors.HumanError(err, apiEndpoints, Tea.ConfigFile("api.yaml"))
if isRPCConnError { if isRPCConnError {
// API节点是否正在启动 // API节点是否正在启动
var sock = gosock.NewTmpSock("edge-api") var sock = gosock.NewTmpSock("edge-api")

View File

@@ -67,5 +67,5 @@ func (this *OtpQrcodeAction) RunGet(params struct {
return return
} }
this.AddHeader("Content-Type", "image/png") this.AddHeader("Content-Type", "image/png")
this.Write(data) _, _ = this.Write(data)
} }

View File

@@ -297,7 +297,7 @@ func (this *DetailAction) RunGet(params struct {
} }
// 缓存硬盘 & 内存容量 // 缓存硬盘 & 内存容量
var maxCacheDiskCapacity maps.Map = nil var maxCacheDiskCapacity maps.Map
if node.MaxCacheDiskCapacity != nil { if node.MaxCacheDiskCapacity != nil {
maxCacheDiskCapacity = maps.Map{ maxCacheDiskCapacity = maps.Map{
"count": node.MaxCacheDiskCapacity.Count, "count": node.MaxCacheDiskCapacity.Count,
@@ -310,7 +310,7 @@ func (this *DetailAction) RunGet(params struct {
} }
} }
var maxCacheMemoryCapacity maps.Map = nil var maxCacheMemoryCapacity maps.Map
if node.MaxCacheMemoryCapacity != nil { if node.MaxCacheMemoryCapacity != nil {
maxCacheMemoryCapacity = maps.Map{ maxCacheMemoryCapacity = maps.Map{
"count": node.MaxCacheMemoryCapacity.Count, "count": node.MaxCacheMemoryCapacity.Count,

View File

@@ -33,7 +33,7 @@ func (this *IndexAction) RunGet(params struct {
} }
// 缓存硬盘 & 内存容量 // 缓存硬盘 & 内存容量
var maxCacheDiskCapacity maps.Map = nil var maxCacheDiskCapacity maps.Map
if node.MaxCacheDiskCapacity != nil { if node.MaxCacheDiskCapacity != nil {
maxCacheDiskCapacity = maps.Map{ maxCacheDiskCapacity = maps.Map{
"count": node.MaxCacheDiskCapacity.Count, "count": node.MaxCacheDiskCapacity.Count,
@@ -46,7 +46,7 @@ func (this *IndexAction) RunGet(params struct {
} }
} }
var maxCacheMemoryCapacity maps.Map = nil var maxCacheMemoryCapacity maps.Map
if node.MaxCacheMemoryCapacity != nil { if node.MaxCacheMemoryCapacity != nil {
maxCacheMemoryCapacity = maps.Map{ maxCacheMemoryCapacity = maps.Map{
"count": node.MaxCacheMemoryCapacity.Count, "count": node.MaxCacheMemoryCapacity.Count,

View File

@@ -43,7 +43,7 @@ func (this *IndexAction) RunGet(params struct {
} }
this.Data["config"] = config this.Data["config"] = config
var httpAllDomainMismatchActionContentHTML = "" var httpAllDomainMismatchActionContentHTML string
var httpAllDomainMismatchActionStatusCode = "404" var httpAllDomainMismatchActionStatusCode = "404"
if config.HTTPAll.DomainMismatchAction != nil && config.HTTPAll.DomainMismatchAction.Options != nil { if config.HTTPAll.DomainMismatchAction != nil && config.HTTPAll.DomainMismatchAction.Options != nil {
httpAllDomainMismatchActionContentHTML = config.HTTPAll.DomainMismatchAction.Options.GetString("contentHTML") httpAllDomainMismatchActionContentHTML = config.HTTPAll.DomainMismatchAction.Options.GetString("contentHTML")

View File

@@ -19,7 +19,7 @@ func (this *Helper) BeforeAction(action *actions.ActionObject) {
action.Data["teaMenu"] = "db" action.Data["teaMenu"] = "db"
selectedTabbar, _ := action.Data["mainTab"] var selectedTabbar = action.Data["mainTab"]
var tabbar = actionutils.NewTabbar() var tabbar = actionutils.NewTabbar()
tabbar.Add(this.Lang(action, codes.DBNode_TabNodes), "", "/db", "", selectedTabbar == "db") tabbar.Add(this.Lang(action, codes.DBNode_TabNodes), "", "/db", "", selectedTabbar == "db")

View File

@@ -63,6 +63,10 @@ func (this *LogsAction) RunGet(params struct {
Offset: page.Offset, Offset: page.Offset,
Size: page.Size, Size: page.Size,
}) })
if err != nil {
this.ErrorPage(err)
return
}
logs := []maps.Map{} logs := []maps.Map{}
for _, log := range logsResp.NodeLogs { for _, log := range logsResp.NodeLogs {

View File

@@ -101,9 +101,7 @@ func ValidateRecordValue(recordType dnsconfigs.RecordType, value string) (messag
return return
} }
case dnsconfigs.RecordTypeCNAME: case dnsconfigs.RecordTypeCNAME:
if strings.HasSuffix(value, ".") { value = strings.TrimSuffix(value, ".")
value = value[:len(value)-1]
}
if !strings.Contains(value, ".") || !ValidateDomainFormat(value) { if !strings.Contains(value, ".") || !ValidateDomainFormat(value) {
message = "请输入正确的域名" message = "请输入正确的域名"
return return
@@ -118,17 +116,13 @@ func ValidateRecordValue(recordType dnsconfigs.RecordType, value string) (messag
return return
} }
case dnsconfigs.RecordTypeNS: case dnsconfigs.RecordTypeNS:
if strings.HasSuffix(value, ".") { value = strings.TrimSuffix(value, ".")
value = value[:len(value)-1]
}
if !strings.Contains(value, ".") || !ValidateDomainFormat(value) { if !strings.Contains(value, ".") || !ValidateDomainFormat(value) {
message = "请输入正确的DNS服务器域名" message = "请输入正确的DNS服务器域名"
return return
} }
case dnsconfigs.RecordTypeMX: case dnsconfigs.RecordTypeMX:
if strings.HasSuffix(value, ".") { value = strings.TrimSuffix(value, ".")
value = value[:len(value)-1]
}
if !strings.Contains(value, ".") || !ValidateDomainFormat(value) { if !strings.Contains(value, ".") || !ValidateDomainFormat(value) {
message = "请输入正确的邮件服务器域名" message = "请输入正确的邮件服务器域名"
return return

View File

@@ -28,7 +28,7 @@ func (this *IndexAction) RunGet(params struct {
// 格式化域名 // 格式化域名
var domain = params.Domain var domain = params.Domain
domain = regexp.MustCompile(`^(www\.)`).ReplaceAllString(params.Domain, "") domain = regexp.MustCompile(`^(www\.)`).ReplaceAllString(domain, "")
domain = strings.ToLower(domain) domain = strings.ToLower(domain)
countResp, err := this.RPC().DNSProviderRPC().CountAllEnabledDNSProviders(this.AdminContext(), &pb.CountAllEnabledDNSProvidersRequest{ countResp, err := this.RPC().DNSProviderRPC().CountAllEnabledDNSProviders(this.AdminContext(), &pb.CountAllEnabledDNSProvidersRequest{

View File

@@ -57,6 +57,6 @@ func (this *FileAction) RunGet(params struct {
if chunkResp.FileChunk == nil { if chunkResp.FileChunk == nil {
continue continue
} }
this.Write(chunkResp.FileChunk.Data) _, _ = this.Write(chunkResp.FileChunk.Data)
} }
} }

View File

@@ -123,5 +123,5 @@ func (this *ExportExcelAction) RunGet(params struct {
} }
this.AddHeader("Content-Length", strconv.Itoa(buf.Len())) this.AddHeader("Content-Length", strconv.Itoa(buf.Len()))
this.Write(buf.Bytes()) _, _ = this.Write(buf.Bytes())
} }

View File

@@ -36,7 +36,7 @@ func UpdateNodeIPAddresses(parentAction *actionutils.ParentAction, nodeId int64,
if addrId > 0 { if addrId > 0 {
resultAddrIds = append(resultAddrIds, addrId) resultAddrIds = append(resultAddrIds, addrId)
var isOn = false var isOn bool
if !addr.Has("isOn") { // 兼容老版本 if !addr.Has("isOn") { // 兼容老版本
isOn = true isOn = true
} else { } else {

View File

@@ -36,5 +36,5 @@ func (this *DownloadCertAction) RunGet(params struct {
} }
this.AddHeader("Content-Disposition", "attachment; filename=\"cert-"+strconv.FormatInt(params.CertId, 10)+".pem\";") this.AddHeader("Content-Disposition", "attachment; filename=\"cert-"+strconv.FormatInt(params.CertId, 10)+".pem\";")
this.Write(certConfig.CertData) _, _ = this.Write(certConfig.CertData)
} }

View File

@@ -36,5 +36,5 @@ func (this *DownloadKeyAction) RunGet(params struct {
} }
this.AddHeader("Content-Disposition", "attachment; filename=\"key-"+strconv.FormatInt(params.CertId, 10)+".pem\";") this.AddHeader("Content-Disposition", "attachment; filename=\"key-"+strconv.FormatInt(params.CertId, 10)+".pem\";")
this.Write(certConfig.KeyData) _, _ = this.Write(certConfig.KeyData)
} }

View File

@@ -50,12 +50,12 @@ func (this *IndexAction) RunGet(params struct {
} }
this.Data["user"] = userMap this.Data["user"] = userMap
var countAll = int64(0) var countAll int64
var countCA = int64(0) var countCA int64
var countAvailable = int64(0) var countAvailable int64
var countExpired = int64(0) var countExpired int64
var count7Days = int64(0) var count7Days int64
var count30Days = int64(0) var count30Days int64
// 计算数量 // 计算数量
{ {

View File

@@ -172,6 +172,11 @@ func (this *SelectPopupAction) RunGet(params struct {
}) })
} }
if err != nil {
this.ErrorPage(err)
return
}
if listResp == nil { if listResp == nil {
this.ErrorPage(errors.New("'listResp' should not be nil")) this.ErrorPage(errors.New("'listResp' should not be nil"))
return return

View File

@@ -1,6 +1,7 @@
package certs package certs
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes" "github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
@@ -120,7 +121,7 @@ func (this *UpdatePopupAction) RunPost(params struct {
// 校验 // 校验
certConfig.IsCA = params.IsCA certConfig.IsCA = params.IsCA
err = certConfig.Init(nil) err = certConfig.Init(context.TODO())
if err != nil { if err != nil {
if params.IsCA { if params.IsCA {
this.Fail("证书校验错误:" + err.Error()) this.Fail("证书校验错误:" + err.Error())

View File

@@ -4,6 +4,7 @@ package certs
import ( import (
"bytes" "bytes"
"context"
"crypto/tls" "crypto/tls"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes" "github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
@@ -156,7 +157,7 @@ func (this *UploadBatchPopupAction) RunPost(params struct {
CertData: certData, CertData: certData,
KeyData: keyData, KeyData: keyData,
} }
err := certConfig.Init(nil) err := certConfig.Init(context.TODO())
if err != nil { if err != nil {
this.Fail("证书验证失败:" + err.Error()) this.Fail("证书验证失败:" + err.Error())
return return

View File

@@ -1,6 +1,7 @@
package certs package certs
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes" "github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
@@ -60,8 +61,8 @@ func (this *UploadPopupAction) RunPost(params struct {
Field("name", params.Name). Field("name", params.Name).
Require("请输入证书说明") Require("请输入证书说明")
var certData = []byte{} var certData []byte
var keyData = []byte{} var keyData []byte
if params.TextMode { if params.TextMode {
if len(params.CertText) == 0 { if len(params.CertText) == 0 {
@@ -104,7 +105,7 @@ func (this *UploadPopupAction) RunPost(params struct {
CertData: certData, CertData: certData,
KeyData: keyData, KeyData: keyData,
} }
err := certConfig.Init(nil) err := certConfig.Init(context.TODO())
if err != nil { if err != nil {
if params.IsCA { if params.IsCA {
this.Fail("证书校验错误:" + err.Error()) this.Fail("证书校验错误:" + err.Error())

View File

@@ -35,5 +35,5 @@ func (this *ViewCertAction) RunGet(params struct {
this.ErrorPage(err) this.ErrorPage(err)
return return
} }
this.Write(certConfig.CertData) _, _ = this.Write(certConfig.CertData)
} }

View File

@@ -30,5 +30,5 @@ func (this *ViewKeyAction) RunGet(params struct {
this.ErrorPage(err) this.ErrorPage(err)
return return
} }
this.Write(certConfig.KeyData) _, _ = this.Write(certConfig.KeyData)
} }

View File

@@ -5,7 +5,6 @@ import (
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/components/cache/cacheutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/components/cache/cacheutils"
"github.com/iwind/TeaGo/actions" "github.com/iwind/TeaGo/actions"
"net/http" "net/http"
"reflect"
) )
type Helper struct { type Helper struct {
@@ -27,11 +26,11 @@ func (this *Helper) BeforeAction(actionPtr actions.ActionWrapper) {
cachePolicyId := action.ParamInt64("cachePolicyId") cachePolicyId := action.ParamInt64("cachePolicyId")
action.Data["cachePolicyId"] = cachePolicyId action.Data["cachePolicyId"] = cachePolicyId
parentActionValue := reflect.ValueOf(actionPtr).Elem().FieldByName("ParentAction") parentActionObj, ok := actionPtr.(interface {
if parentActionValue.IsValid() { Parent() *actionutils.ParentAction
parentAction, isOk := parentActionValue.Interface().(actionutils.ParentAction) })
if isOk { if ok {
action.Data["cachePolicyName"] = cacheutils.FindCachePolicyNameWithoutError(&parentAction, cachePolicyId) var parentAction = parentActionObj.Parent()
} action.Data["cachePolicyName"] = cacheutils.FindCachePolicyNameWithoutError(parentAction, cachePolicyId)
} }
} }

View File

@@ -76,14 +76,6 @@ func (this *IndexAction) RunPost(params struct {
this.Fail("配置校验失败:" + err.Error()) this.Fail("配置校验失败:" + err.Error())
} }
// 允许不匹配的域名
allowMismatchDomains := []string{}
for _, domain := range params.AllowMismatchDomains {
if len(domain) > 0 {
allowMismatchDomains = append(allowMismatchDomains, domain)
}
}
// TCP端口范围 // TCP端口范围
if params.TcpAllPortRangeMin < 1024 { if params.TcpAllPortRangeMin < 1024 {
params.TcpAllPortRangeMin = 1024 params.TcpAllPortRangeMin = 1024

View File

@@ -31,7 +31,7 @@ func (this *ExportDownloadAction) RunGet(params struct {
if ok { if ok {
this.AddHeader("Content-Disposition", "attachment; filename=\"WAF-"+types.String(params.PolicyId)+".json\";") this.AddHeader("Content-Disposition", "attachment; filename=\"WAF-"+types.String(params.PolicyId)+".json\";")
this.AddHeader("Content-Length", strconv.Itoa(len(data))) this.AddHeader("Content-Length", strconv.Itoa(len(data)))
this.Write(data) _, _ = this.Write(data)
} else { } else {
this.WriteString("找不到要导出的内容") this.WriteString("找不到要导出的内容")
return return

View File

@@ -52,6 +52,10 @@ func (this *SortSetsAction) RunPost(params struct {
FirewallRuleGroupId: params.GroupId, FirewallRuleGroupId: params.GroupId,
FirewallRuleSetsJSON: newRefsJSON, FirewallRuleSetsJSON: newRefsJSON,
}) })
if err != nil {
this.ErrorPage(err)
return
}
this.Success() this.Success()
} }

View File

@@ -1,6 +1,7 @@
package httpReverseProxy package httpReverseProxy
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/groups/group/servergrouputils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/groups/group/servergrouputils"
@@ -73,7 +74,7 @@ func (this *SettingAction) RunPost(params struct {
return return
} }
err = reverseProxyConfig.Init(nil) err = reverseProxyConfig.Init(context.TODO())
if err != nil { if err != nil {
this.Fail("配置校验失败:" + err.Error()) this.Fail("配置校验失败:" + err.Error())
} }

View File

@@ -1,6 +1,7 @@
package tcpReverseProxy package tcpReverseProxy
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/groups/group/servergrouputils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/groups/group/servergrouputils"
@@ -73,7 +74,7 @@ func (this *SettingAction) RunPost(params struct {
return return
} }
err = reverseProxyConfig.Init(nil) err = reverseProxyConfig.Init(context.TODO())
if err != nil { if err != nil {
this.Fail("配置校验失败:" + err.Error()) this.Fail("配置校验失败:" + err.Error())
} }

View File

@@ -1,6 +1,7 @@
package udpReverseProxy package udpReverseProxy
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/groups/group/servergrouputils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/groups/group/servergrouputils"
@@ -73,7 +74,7 @@ func (this *SettingAction) RunPost(params struct {
return return
} }
err = reverseProxyConfig.Init(nil) err = reverseProxyConfig.Init(context.TODO())
if err != nil { if err != nil {
this.Fail("配置校验失败:" + err.Error()) this.Fail("配置校验失败:" + err.Error())
} }

View File

@@ -102,6 +102,10 @@ func (this *IndexAction) RunPost(params struct {
RequestSameOrigin: websocketConfig.RequestSameOrigin, RequestSameOrigin: websocketConfig.RequestSameOrigin,
RequestOrigin: websocketConfig.RequestOrigin, RequestOrigin: websocketConfig.RequestOrigin,
}) })
if err != nil {
this.ErrorPage(err)
return
}
} }
websocketRef.WebsocketId = websocketConfig.Id websocketRef.WebsocketId = websocketConfig.Id

View File

@@ -31,7 +31,7 @@ func (this *ExportDataAction) RunGet(params struct {
defer this.CreateLogInfo(codes.IPList_LogExportIPList, params.ListId) defer this.CreateLogInfo(codes.IPList_LogExportIPList, params.ListId)
var err error var err error
var ext = "" var ext string
var jsonMaps = []maps.Map{} var jsonMaps = []maps.Map{}
var xlsxFile *xlsx.File var xlsxFile *xlsx.File
var xlsxSheet *xlsx.Sheet var xlsxSheet *xlsx.Sheet
@@ -146,5 +146,5 @@ func (this *ExportDataAction) RunGet(params struct {
this.AddHeader("Content-Disposition", "attachment; filename=\"ip-list-"+numberutils.FormatInt64(params.ListId)+ext+"\";") this.AddHeader("Content-Disposition", "attachment; filename=\"ip-list-"+numberutils.FormatInt64(params.ListId)+ext+"\";")
this.AddHeader("Content-Length", strconv.Itoa(len(data))) this.AddHeader("Content-Length", strconv.Itoa(len(data)))
this.Write(data) _, _ = this.Write(data)
} }

View File

@@ -1,6 +1,7 @@
package http package http
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/serverutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/default/servers/serverutils"
@@ -53,7 +54,7 @@ func (this *IndexAction) RunGet(params struct {
this.ErrorPage(err) this.ErrorPage(err)
return return
} }
_ = httpsConfig.Init(nil) _ = httpsConfig.Init(context.TODO())
for _, port := range httpsConfig.AllPorts() { for _, port := range httpsConfig.AllPorts() {
if lists.ContainsInt(httpPorts, port) { if lists.ContainsInt(httpPorts, port) {
conflictingPorts = append(conflictingPorts, port) conflictingPorts = append(conflictingPorts, port)

View File

@@ -1,6 +1,7 @@
package https package https
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
@@ -43,7 +44,7 @@ func (this *IndexAction) RunGet(params struct {
httpsConfig.IsOn = true httpsConfig.IsOn = true
} }
_ = httpsConfig.Init(nil) _ = httpsConfig.Init(context.TODO())
var httpsPorts = httpsConfig.AllPorts() var httpsPorts = httpsConfig.AllPorts()
// 检查http和https端口冲突 // 检查http和https端口冲突

View File

@@ -32,18 +32,18 @@ func (this *RequestCertPopupAction) RunGet(params struct {
return return
} }
serverNameConfigs := []*serverconfigs.ServerNameConfig{} var serverNameConfigs = []*serverconfigs.ServerNameConfig{}
err = json.Unmarshal(serverNamesResp.ServerNamesJSON, &serverNameConfigs) err = json.Unmarshal(serverNamesResp.ServerNamesJSON, &serverNameConfigs)
if err != nil { if err != nil {
this.ErrorPage(err) this.ErrorPage(err)
return return
} }
excludeServerNames := []string{} var excludeServerNames = []string{}
if len(params.ExcludeServerNames) > 0 { if len(params.ExcludeServerNames) > 0 {
excludeServerNames = strings.Split(params.ExcludeServerNames, ",") excludeServerNames = strings.Split(params.ExcludeServerNames, ",")
} }
serverNames := []string{} var serverNames = []string{}
for _, c := range serverNameConfigs { for _, c := range serverNameConfigs {
if len(c.SubNames) == 0 { if len(c.SubNames) == 0 {
if domainutils.ValidateDomainFormat(c.Name) && !lists.ContainsString(excludeServerNames, c.Name) { if domainutils.ValidateDomainFormat(c.Name) && !lists.ContainsString(excludeServerNames, c.Name) {
@@ -64,7 +64,12 @@ func (this *RequestCertPopupAction) RunGet(params struct {
AdminId: this.AdminId(), AdminId: this.AdminId(),
UserId: 0, UserId: 0,
}) })
userMaps := []maps.Map{} if err != nil {
this.ErrorPage(err)
return
}
var userMaps = []maps.Map{}
for _, user := range acmeUsersResp.AcmeUsers { for _, user := range acmeUsersResp.AcmeUsers {
description := user.Description description := user.Description
if len(description) > 0 { if len(description) > 0 {

View File

@@ -52,6 +52,10 @@ func (this *IndexAction) RunGet(params struct {
HttpWebId: webId, HttpWebId: webId,
HeaderJSON: refJSON, HeaderJSON: refJSON,
}) })
if err != nil {
this.ErrorPage(err)
return
}
isChanged = true isChanged = true
} }
if webConfig.ResponseHeaderPolicy == nil { if webConfig.ResponseHeaderPolicy == nil {
@@ -75,6 +79,10 @@ func (this *IndexAction) RunGet(params struct {
HttpWebId: webId, HttpWebId: webId,
HeaderJSON: refJSON, HeaderJSON: refJSON,
}) })
if err != nil {
this.ErrorPage(err)
return
}
isChanged = true isChanged = true
} }

View File

@@ -8,7 +8,6 @@ import (
"github.com/iwind/TeaGo/actions" "github.com/iwind/TeaGo/actions"
"github.com/iwind/TeaGo/maps" "github.com/iwind/TeaGo/maps"
"net/http" "net/http"
"reflect"
) )
type LocationHelper struct { type LocationHelper struct {
@@ -35,19 +34,19 @@ func (this *LocationHelper) BeforeAction(actionPtr actions.ActionWrapper) {
// 路径信息 // 路径信息
var currentLocationConfig *serverconfigs.HTTPLocationConfig = nil var currentLocationConfig *serverconfigs.HTTPLocationConfig = nil
parentActionValue := reflect.ValueOf(actionPtr).Elem().FieldByName("ParentAction") parentActionValue, ok := actionPtr.(interface {
if parentActionValue.IsValid() { Parent() *actionutils.ParentAction
parentAction, isOk := parentActionValue.Interface().(actionutils.ParentAction) })
if isOk { if ok {
var locationId = action.ParamInt64("locationId") var parentAction = parentActionValue.Parent()
locationConfig, isOk := FindLocationConfig(&parentAction, locationId) var locationId = action.ParamInt64("locationId")
if !isOk { locationConfig, isOk := FindLocationConfig(parentAction, locationId)
return if !isOk {
} return
action.Data["locationId"] = locationId
action.Data["locationConfig"] = locationConfig
currentLocationConfig = locationConfig
} }
action.Data["locationId"] = locationId
action.Data["locationConfig"] = locationConfig
currentLocationConfig = locationConfig
} }
// 左侧菜单 // 左侧菜单

View File

@@ -1,6 +1,7 @@
package locationutils package locationutils
import ( import (
"context"
"encoding/json" "encoding/json"
"errors" "errors"
"github.com/TeaOSLab/EdgeAdmin/internal/utils" "github.com/TeaOSLab/EdgeAdmin/internal/utils"
@@ -30,7 +31,7 @@ func FindLocationConfig(parentAction *actionutils.ParentAction, locationId int64
return return
} }
err = locationConfig.Init(nil) err = locationConfig.Init(context.TODO())
if err != nil { if err != nil {
parentAction.ErrorPage(err) parentAction.ErrorPage(err)
return return

View File

@@ -1,6 +1,7 @@
package reverseProxy package reverseProxy
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes" "github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
@@ -64,7 +65,7 @@ func (this *SettingAction) RunPost(params struct {
return return
} }
err = reverseProxyConfig.Init(nil) err = reverseProxyConfig.Init(context.TODO())
if err != nil { if err != nil {
this.Fail("配置校验失败:" + err.Error()) this.Fail("配置校验失败:" + err.Error())
} }

View File

@@ -94,6 +94,10 @@ func (this *IndexAction) RunPost(params struct {
RequestSameOrigin: websocketConfig.RequestSameOrigin, RequestSameOrigin: websocketConfig.RequestSameOrigin,
RequestOrigin: websocketConfig.RequestOrigin, RequestOrigin: websocketConfig.RequestOrigin,
}) })
if err != nil {
this.ErrorPage(err)
return
}
} }
websocketRef.WebsocketId = websocketConfig.Id websocketRef.WebsocketId = websocketConfig.Id

View File

@@ -31,7 +31,7 @@ func (this *AddPopupAction) RunGet(params struct {
this.Data["reverseProxyId"] = params.ReverseProxyId this.Data["reverseProxyId"] = params.ReverseProxyId
this.Data["originType"] = params.OriginType this.Data["originType"] = params.OriginType
var serverType = "" var serverType string
if params.ServerId > 0 { if params.ServerId > 0 {
serverTypeResp, err := this.RPC().ServerRPC().FindEnabledServerType(this.AdminContext(), &pb.FindEnabledServerTypeRequest{ServerId: params.ServerId}) serverTypeResp, err := this.RPC().ServerRPC().FindEnabledServerType(this.AdminContext(), &pb.FindEnabledServerTypeRequest{ServerId: params.ServerId})
if err != nil { if err != nil {

View File

@@ -37,7 +37,7 @@ func (this *UpdatePopupAction) RunGet(params struct {
this.Data["reverseProxyId"] = params.ReverseProxyId this.Data["reverseProxyId"] = params.ReverseProxyId
this.Data["originId"] = params.OriginId this.Data["originId"] = params.OriginId
var serverType = "" var serverType string
if params.ServerId > 0 { if params.ServerId > 0 {
serverTypeResp, err := this.RPC().ServerRPC().FindEnabledServerType(this.AdminContext(), &pb.FindEnabledServerTypeRequest{ serverTypeResp, err := this.RPC().ServerRPC().FindEnabledServerType(this.AdminContext(), &pb.FindEnabledServerTypeRequest{
ServerId: params.ServerId, ServerId: params.ServerId,

View File

@@ -1,6 +1,7 @@
package reverseProxy package reverseProxy
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
"github.com/TeaOSLab/EdgeCommon/pkg/langs/codes" "github.com/TeaOSLab/EdgeCommon/pkg/langs/codes"
@@ -63,7 +64,7 @@ func (this *SettingAction) RunPost(params struct {
return return
} }
err = reverseProxyConfig.Init(nil) err = reverseProxyConfig.Init(context.TODO())
if err != nil { if err != nil {
this.Fail("配置校验失败:" + err.Error()) this.Fail("配置校验失败:" + err.Error())
} }

View File

@@ -107,6 +107,10 @@ func (this *IndexAction) RunPost(params struct {
RequestSameOrigin: websocketConfig.RequestSameOrigin, RequestSameOrigin: websocketConfig.RequestSameOrigin,
RequestOrigin: websocketConfig.RequestOrigin, RequestOrigin: websocketConfig.RequestOrigin,
}) })
if err != nil {
this.ErrorPage(err)
return
}
} }
websocketRef.WebsocketId = websocketConfig.Id websocketRef.WebsocketId = websocketConfig.Id

View File

@@ -43,8 +43,8 @@ func (this *ServerHelper) createLeftMenu(action *actions.ActionObject) {
action.Data["leftMenuItemIsDisabled"] = false action.Data["leftMenuItemIsDisabled"] = false
} }
action.Data["leftMenuItems"] = []maps.Map{} action.Data["leftMenuItems"] = []maps.Map{}
mainTab, _ := action.Data["mainTab"] var mainTab = action.Data["mainTab"]
secondMenuItem, _ := action.Data["secondMenuItem"] var secondMenuItem = action.Data["secondMenuItem"]
serverId := action.ParamInt64("serverId") serverId := action.ParamInt64("serverId")
if serverId == 0 { if serverId == 0 {
@@ -108,7 +108,7 @@ func (this *ServerHelper) createLeftMenu(action *actions.ActionObject) {
action.Data["serverFamily"] = family action.Data["serverFamily"] = family
// TABBAR // TABBAR
selectedTabbar, _ := action.Data["mainTab"] var selectedTabbar = action.Data["mainTab"]
var tabbar = actionutils.NewTabbar() var tabbar = actionutils.NewTabbar()
tabbar.Add("", "", "/servers", "left arrow", false) tabbar.Add("", "", "/servers", "left arrow", false)
if len(serverConfig.Name) > 0 { if len(serverConfig.Name) > 0 {

View File

@@ -1,6 +1,7 @@
package api package api
import ( import (
"context"
"encoding/json" "encoding/json"
"fmt" "fmt"
teaconst "github.com/TeaOSLab/EdgeAdmin/internal/const" teaconst "github.com/TeaOSLab/EdgeAdmin/internal/const"
@@ -82,7 +83,7 @@ func (this *IndexAction) RunGet(params struct{}) {
this.ErrorPage(err) this.ErrorPage(err)
return return
} }
_ = httpsConfig.Init(nil) _ = httpsConfig.Init(context.TODO())
if httpsConfig.IsOn && len(httpsConfig.Listen) > 0 { if httpsConfig.IsOn && len(httpsConfig.Listen) > 0 {
restAccessAddrs = append(restAccessAddrs, httpsConfig.FullAddresses()...) restAccessAddrs = append(restAccessAddrs, httpsConfig.FullAddresses()...)
} }

View File

@@ -59,8 +59,8 @@ func (this *LogsAction) RunGet(params struct {
this.ErrorPage(err) this.ErrorPage(err)
return return
} }
count := countResp.Count var count = countResp.Count
page := this.NewPage(count, 20) var page = this.NewPage(count, 20)
logsResp, err := this.RPC().NodeLogRPC().ListNodeLogs(this.AdminContext(), &pb.ListNodeLogsRequest{ logsResp, err := this.RPC().NodeLogRPC().ListNodeLogs(this.AdminContext(), &pb.ListNodeLogsRequest{
NodeId: params.NodeId, NodeId: params.NodeId,
@@ -73,8 +73,12 @@ func (this *LogsAction) RunGet(params struct {
Offset: page.Offset, Offset: page.Offset,
Size: page.Size, Size: page.Size,
}) })
if err != nil {
this.ErrorPage(err)
return
}
logs := []maps.Map{} var logs = []maps.Map{}
for _, log := range logsResp.NodeLogs { for _, log := range logsResp.NodeLogs {
logs = append(logs, maps.Map{ logs = append(logs, maps.Map{
"tag": log.Tag, "tag": log.Tag,

View File

@@ -1,6 +1,7 @@
package server package server
import ( import (
"context"
"encoding/json" "encoding/json"
"github.com/TeaOSLab/EdgeAdmin/internal/utils" "github.com/TeaOSLab/EdgeAdmin/internal/utils"
"github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils" "github.com/TeaOSLab/EdgeAdmin/internal/web/actions/actionutils"
@@ -49,7 +50,7 @@ func (this *UpdateHTTPSPopupAction) RunGet(params struct{}) {
CertData: certData, CertData: certData,
KeyData: keyData, KeyData: keyData,
} }
_ = certConfig.Init(nil) _ = certConfig.Init(context.TODO())
certConfig.CertData = nil certConfig.CertData = nil
certConfig.KeyData = nil certConfig.KeyData = nil
certConfigs = append(certConfigs, certConfig) certConfigs = append(certConfigs, certConfig)

View File

@@ -286,7 +286,7 @@ func (this *MySQLInstaller) InstallFromFile(xzFilePath string, targetDir string)
// initialize // initialize
this.log("initializing mysql ...") this.log("initializing mysql ...")
var generatedPassword = "" var generatedPassword string
{ {
var cmd = utils.NewCmd(baseDir+"/bin/mysqld", "--initialize", "--user=mysql") var cmd = utils.NewCmd(baseDir+"/bin/mysqld", "--initialize", "--user=mysql")
cmd.WithStderr() cmd.WithStderr()

View File

@@ -77,16 +77,23 @@ func (this *ValidateDbAction) RunPost(params struct {
Dsn: params.Username + ":" + params.Password + "@tcp(" + configutils.QuoteIP(params.Host) + ":" + params.Port + ")/", Dsn: params.Username + ":" + params.Password + "@tcp(" + configutils.QuoteIP(params.Host) + ":" + params.Port + ")/",
Prefix: "", Prefix: "",
}) })
if err != nil {
this.Fail("尝试创建数据库失败:" + err.Error())
return
}
_, err = db.Exec("CREATE DATABASE `" + params.Database + "`") _, err = db.Exec("CREATE DATABASE `" + params.Database + "`")
if err != nil { if err != nil {
this.Fail("尝试创建数据库失败:" + err.Error()) this.Fail("尝试创建数据库失败:" + err.Error())
return
} }
} else { } else {
if strings.Contains(err.Error(), "Error 1044:") { if strings.Contains(err.Error(), "Error 1044:") {
this.Fail("无法连接到数据库,权限检查失败:" + err.Error()) this.Fail("无法连接到数据库,权限检查失败:" + err.Error())
return
} }
this.Fail("无法连接到数据库,请检查配置:" + err.Error()) this.Fail("无法连接到数据库,请检查配置:" + err.Error())
return
} }
} }

View File

@@ -142,5 +142,5 @@ func (this *ComponentsAction) RunGet(params struct{}) {
componentsDataSum = fmt.Sprintf("%x", h.Sum(nil)) componentsDataSum = fmt.Sprintf("%x", h.Sum(nil))
this.AddHeader("ETag", "\""+componentsDataSum+"\"") this.AddHeader("ETag", "\""+componentsDataSum+"\"")
this.Write(componentsData) _, _ = this.Write(componentsData)
} }

View File

@@ -63,6 +63,6 @@ func (this *ImageAction) RunGet(params struct {
if chunkResp.FileChunk == nil { if chunkResp.FileChunk == nil {
continue continue
} }
this.Write(chunkResp.FileChunk.Data) _, _ = this.Write(chunkResp.FileChunk.Data)
} }
} }

View File

@@ -71,5 +71,5 @@ func (this *OtpQrcodeAction) RunGet(params struct {
return return
} }
this.AddHeader("Content-Type", "image/png") this.AddHeader("Content-Type", "image/png")
this.Write(data) _, _ = this.Write(data)
} }