Import x-panel source

This commit is contained in:
2026-05-03 11:34:48 +08:00
commit e98e780360
312 changed files with 90189 additions and 0 deletions

28
util/common/err.go Normal file
View File

@@ -0,0 +1,28 @@
package common
import (
"errors"
"fmt"
"x-ui/logger"
)
func NewErrorf(format string, a ...any) error {
msg := fmt.Sprintf(format, a...)
return errors.New(msg)
}
func NewError(a ...any) error {
msg := fmt.Sprintln(a...)
return errors.New(msg)
}
func Recover(msg string) any {
panicErr := recover()
if panicErr != nil {
if msg != "" {
logger.Error(msg, "panic:", panicErr)
}
}
return panicErr
}

17
util/common/format.go Normal file
View File

@@ -0,0 +1,17 @@
package common
import (
"fmt"
)
func FormatTraffic(trafficBytes int64) string {
units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
unitIndex := 0
size := float64(trafficBytes)
for size >= 1024 && unitIndex < len(units)-1 {
size /= 1024
unitIndex++
}
return fmt.Sprintf("%.2f%s", size, units[unitIndex])
}

View File

@@ -0,0 +1,30 @@
package common
import (
"strings"
)
type multiError []error
func (e multiError) Error() string {
var r strings.Builder
r.WriteString("multierr: ")
for _, err := range e {
r.WriteString(err.Error())
r.WriteString(" | ")
}
return r.String()
}
func Combine(maybeError ...error) error {
var errs multiError
for _, err := range maybeError {
if err != nil {
errs = append(errs, err)
}
}
if len(errs) == 0 {
return nil
}
return errs
}

18
util/common/random.go Normal file
View File

@@ -0,0 +1,18 @@
package common
import (
"crypto/rand"
"math/big"
)
// RandomInt 返回一个 0 .. max-1 之间的随机整数(使用 crypto/rand
func RandomInt(max int) int {
if max <= 0 {
return 0
}
n, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
if err != nil {
return 0
}
return int(n.Int64())
}