Skip to content

Commit

Permalink
添加清空流量数据命令
Browse files Browse the repository at this point in the history
  • Loading branch information
Jrohy committed Nov 18, 2020
1 parent 30167e8 commit 54e2227
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 2 deletions.
23 changes: 23 additions & 0 deletions cmd/clean.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package cmd

import (
"github.com/spf13/cobra"
"trojan/trojan"
)

// cleanCmd represents the clean command
var cleanCmd = &cobra.Command{
Use: "clean",
Short: "清空指定用户流量",
Long: `传入指定用户名来清空用户流量, 多个空格隔开, 例如:
trojan clean zhangsan lisi
`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
trojan.CleanDataByName(args)
},
}

func init() {
rootCmd.AddCommand(cleanCmd)
}
29 changes: 27 additions & 2 deletions core/mysql.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,17 @@ import (
"encoding/base64"
"errors"
"fmt"
mysqlDriver "github.com/go-sql-driver/mysql"
"io/ioutil"
"log"
"trojan/util"

mysqlDriver "github.com/go-sql-driver/mysql"

// mysql sql驱动
_ "github.com/go-sql-driver/mysql"
"strconv"
"strings"

_ "github.com/go-sql-driver/mysql"
)

// Mysql 结构体
Expand Down Expand Up @@ -192,6 +194,29 @@ func (mysql *Mysql) CleanData(id uint) error {
return nil
}

// CleanDataByName 清空指定用户名流量统计数据
func (mysql *Mysql) CleanDataByName(usernames []string) error {
db := mysql.GetDB()
if db == nil {
return errors.New("can't connect mysql")
}
defer db.Close()
runSql := "UPDATE users SET download=0, upload=0 WHERE username in ("
for i, name := range usernames {
runSql = runSql + "'" + name + "'"
if i == len(usernames)-1 {
runSql = runSql + ")"
} else {
runSql = runSql + ","
}
}
if _, err := db.Exec(runSql); err != nil {
fmt.Println(err)
return err
}
return nil
}

// GetUserByName 通过用户名来获取用户
func (mysql *Mysql) GetUserByName(name string) *User {
db := mysql.GetDB()
Expand Down
8 changes: 8 additions & 0 deletions trojan/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,14 @@ func CleanData() {
}
}

// CleanDataByName 清空指定用户流量
func CleanDataByName(usernames []string) {
mysql := core.GetMysql()
if err := mysql.CleanDataByName(usernames); err != nil {
fmt.Println(err.Error())
}
}

// UserList 获取用户列表并打印显示
func UserList(ids ...string) []*core.User {
mysql := core.GetMysql()
Expand Down

0 comments on commit 54e2227

Please sign in to comment.