格式化项目代码

pull/23/head
taoshihan1991 4 years ago
parent 2596e46821
commit 1581b69627

@ -18,20 +18,21 @@ var installCmd = &cobra.Command{
install()
},
}
func install(){
sqlFile:=config.Dir+"go-fly.sql"
isExit,_:=tools.IsFileExist(config.MysqlConf)
dataExit,_:=tools.IsFileExist(sqlFile)
if !isExit||!dataExit{
func install() {
sqlFile := config.Dir + "go-fly.sql"
isExit, _ := tools.IsFileExist(config.MysqlConf)
dataExit, _ := tools.IsFileExist(sqlFile)
if !isExit || !dataExit {
fmt.Println("config/mysql.json 数据库配置文件或者数据库文件go-fly.sql不存在")
os.Exit(1)
}
sqls,_:=ioutil.ReadFile(sqlFile)
sqlArr:=strings.Split(string(sqls),";")
for _,sql:=range sqlArr{
if sql==""{
sqls, _ := ioutil.ReadFile(sqlFile)
sqlArr := strings.Split(string(sqls), ";")
for _, sql := range sqlArr {
if sql == "" {
continue
}
models.Execute(sql)
}
}
}

@ -1,21 +1,24 @@
package cmd
import (
"errors"
"fmt"
"github.com/spf13/cobra"
"os"
)
var rootCmd = &cobra.Command{
Use: "go-fly",
Short: "go-fly",
Long: `简洁快速的GO语言WEB在线客服 https://gofly.sopans.com`,
Args:args,
Long: `简洁快速的GO语言WEB在线客服 https://gofly.sopans.com`,
Args: args,
Run: func(cmd *cobra.Command, args []string) {
},
}
func args(cmd *cobra.Command, args []string) error{
if len(args)<1{
func args(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return errors.New("至少需要一个参数!")
}
@ -31,4 +34,4 @@ func init() {
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(serverCmd)
rootCmd.AddCommand(installCmd)
}
}

@ -13,28 +13,30 @@ import (
"os/exec"
"path/filepath"
)
var(
port string
tcpport string
daemon bool
var (
port string
tcpport string
daemon bool
GoflyConfig *config.Config
)
var serverCmd = &cobra.Command{
Use: "server",
Short: "example:go-fly server port 8081",
Use: "server",
Short: "example:go-fly server port 8081",
Example: "go-fly server -c config/",
Run: func(cmd *cobra.Command, args []string) {
run()
},
}
func init() {
serverCmd.PersistentFlags().StringVarP(&port, "port", "p", "8081", "监听端口号")
serverCmd.PersistentFlags().StringVarP(&tcpport, "tcpport", "t", "8082", "监听tcp端口号")
serverCmd.PersistentFlags().BoolVarP(&daemon, "daemon", "d", false, "是否为守护进程模式")
}
func run(){
if daemon==true{
if os.Getppid() != 1{
func run() {
if daemon == true {
if os.Getppid() != 1 {
// 将命令行参数中执行文件路径转换成可用路径
filePath, _ := filepath.Abs(os.Args[0])
cmd := exec.Command(filePath, os.Args[1:]...)
@ -47,7 +49,7 @@ func run(){
}
}
baseServer := "0.0.0.0:"+port
baseServer := "0.0.0.0:" + port
//tcpBaseServer := "0.0.0.0:"+tcpport
log.Println("start server...\r\ngohttp://" + baseServer)
engine := gin.Default()
@ -73,4 +75,4 @@ func run(){
//tcp服务
//go controller.NewTcpServer(tcpBaseServer)
engine.Run(baseServer)
}
}

@ -10,6 +10,6 @@ var versionCmd = &cobra.Command{
Use: "version",
Short: "example:go-fly version",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("go-fly "+config.Version)
fmt.Println("go-fly " + config.Version)
},
}

@ -7,27 +7,31 @@ import (
"io/ioutil"
"os"
)
var(
PageSize uint=10
VisitorPageSize uint=8
Version = "0.1.2"
GoflyConfig *Config
var (
PageSize uint = 10
VisitorPageSize uint = 8
Version = "0.1.2"
GoflyConfig *Config
)
const Dir = "config/"
const AccountConf = Dir + "account.json"
const MysqlConf = Dir + "mysql.json"
const MailConf = Dir + "mail.json"
const LangConf=Dir+"language.json"
const LangConf = Dir + "language.json"
const MainConf = Dir + "config.json"
const WeixinToken=""
const ServerJiang=""
func init(){
const WeixinToken = ""
const ServerJiang = ""
func init() {
//配置文件
GoflyConfig=CreateConfig()
GoflyConfig = CreateConfig()
}
type Mysql struct{
Server string
Port string
type Mysql struct {
Server string
Port string
Database string
Username string
Password string
@ -36,14 +40,15 @@ type MailServer struct {
Server, Email, Password string
}
type Config struct {
Upload string
Upload string
NoticeServerJiang bool
}
func CreateConfig()*Config{
func CreateConfig() *Config {
var configObj Config
c:=&Config{
Upload: "static/upload/",
NoticeServerJiang:false,
c := &Config{
Upload: "static/upload/",
NoticeServerJiang: false,
}
isExist, _ := tools.IsFileExist(MainConf)
if !isExist {

@ -1,43 +1,41 @@
package config
type Language struct {
WebCopyRight string
MainIntro string
Send string
Notice string
IndexSubIntro,IndexVisitors,IndexAgent,IndexDocument,IndexOnlineChat string
WebCopyRight string
MainIntro string
Send string
Notice string
IndexSubIntro, IndexVisitors, IndexAgent, IndexDocument, IndexOnlineChat string
}
func CreateLanguage(lang string)*Language{
func CreateLanguage(lang string) *Language {
var language *Language
if lang=="en"{
language=&Language{
WebCopyRight: "TaoShihan",
MainIntro: "Simple and Powerful Go language online customer chat system",
IndexSubIntro: "GO-FLY, a Vue 2.0-based online customer service instant messaging system for PHP engineers and Golang engineers",
IndexDocument:"API Documents",
IndexVisitors:"Visitors Here",
IndexAgent:"Agents Here",
IndexOnlineChat:"Lets chat. - We're online",
Send:"Send",
Notice:"Hello and welcome to go-fly - how can we help?",
if lang == "en" {
language = &Language{
WebCopyRight: "TaoShihan",
MainIntro: "Simple and Powerful Go language online customer chat system",
IndexSubIntro: "GO-FLY, a Vue 2.0-based online customer service instant messaging system for PHP engineers and Golang engineers",
IndexDocument: "API Documents",
IndexVisitors: "Visitors Here",
IndexAgent: "Agents Here",
IndexOnlineChat: "Lets chat. - We're online",
Send: "Send",
Notice: "Hello and welcome to go-fly - how can we help?",
}
}
if lang=="cn"{
language=&Language{
WebCopyRight: "陶士涵的菜地版权所有",
MainIntro:"极简强大的Go语言在线客服系统",
IndexSubIntro:"GO-FLY一套为PHP工程师、Golang工程师准备的基于 Vue 2.0的在线客服即时通讯系统",
IndexVisitors:"访客入口",
IndexAgent:"客服入口",
IndexDocument:"接口文档",
IndexOnlineChat:"在线咨询",
Send:"发送",
Notice:"欢迎您访问go-fly有什么我能帮助您的",
if lang == "cn" {
language = &Language{
WebCopyRight: "陶士涵的菜地版权所有",
MainIntro: "极简强大的Go语言在线客服系统",
IndexSubIntro: "GO-FLY一套为PHP工程师、Golang工程师准备的基于 Vue 2.0的在线客服即时通讯系统",
IndexVisitors: "访客入口",
IndexAgent: "客服入口",
IndexDocument: "接口文档",
IndexOnlineChat: "在线咨询",
Send: "发送",
Notice: "欢迎您访问go-fly有什么我能帮助您的",
}
}
return language
}

@ -25,15 +25,15 @@ func CheckPass(username string, password string) string {
}
return ""
}
func CheckKefuPass(username string, password string) (models.User,models.User_role,bool) {
info:=models.FindUser(username)
func CheckKefuPass(username string, password string) (models.User, models.User_role, bool) {
info := models.FindUser(username)
var uRole models.User_role
if info.Name==""||info.Password!=tools.Md5(password){
return info,uRole,false
if info.Name == "" || info.Password != tools.Md5(password) {
return info, uRole, false
}
uRole=models.FindRoleByUserId(info.ID)
uRole = models.FindRoleByUserId(info.ID)
return info,uRole,true
return info, uRole, true
}
func AuthLocal(username string, password string) string {
account := config.GetAccount()

@ -9,19 +9,21 @@ import (
"sort"
"time"
)
type vistor struct{
conn *websocket.Conn
name string
id string
type vistor struct {
conn *websocket.Conn
name string
id string
avator string
to_id string
to_id string
}
type Message struct{
conn *websocket.Conn
c *gin.Context
content []byte
type Message struct {
conn *websocket.Conn
c *gin.Context
content []byte
messageType int
}
var clientList = make(map[string]*vistor)
var kefuList = make(map[string][]*websocket.Conn)
var message = make(chan *Message)
@ -31,21 +33,22 @@ type TypeMessage struct {
Data interface{} `json:"data"`
}
type ClientMessage struct {
Name string `json:"name"`
Avator string `json:"avator"`
Id string `json:"id"`
VisitorId string `json:"visitor_id"`
Group string `json:"group"`
Time string `json:"time"`
ToId string `json:"to_id"`
Content string `json:"content"`
City string `json:"city"`
Name string `json:"name"`
Avator string `json:"avator"`
Id string `json:"id"`
VisitorId string `json:"visitor_id"`
Group string `json:"group"`
Time string `json:"time"`
ToId string `json:"to_id"`
Content string `json:"content"`
City string `json:"city"`
ClientIp string `json:"client_ip"`
Refer string `json:"refer"`
Refer string `json:"refer"`
}
//定时检测客户端是否在线
func init() {
upgrader=websocket.Upgrader{
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
@ -55,8 +58,8 @@ func init() {
//sendPingToClient()
}
func NewChatServer(c *gin.Context){
conn,err:=upgrader.Upgrade(c.Writer,c.Request,nil)
func NewChatServer(c *gin.Context) {
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
log.Print("upgrade:", err)
return
@ -67,11 +70,11 @@ func NewChatServer(c *gin.Context){
var recevString string
messageType, receive, err := conn.ReadMessage()
if err != nil {
for uid,visitor :=range clientList{
if visitor.conn==conn{
log.Println("删除用户",uid)
delete(clientList,uid)
models.UpdateVisitorStatus(uid,0)
for uid, visitor := range clientList {
if visitor.conn == conn {
log.Println("删除用户", uid)
delete(clientList, uid)
models.UpdateVisitorStatus(uid, 0)
userInfo := make(map[string]string)
userInfo["uid"] = uid
userInfo["name"] = visitor.name
@ -80,10 +83,10 @@ func NewChatServer(c *gin.Context){
Data: userInfo,
}
str, _ := json.Marshal(msg)
kefuConns:=kefuList[visitor.to_id]
if kefuConns!=nil{
for _,kefuConn:=range kefuConns{
kefuConn.WriteMessage(websocket.TextMessage,str)
kefuConns := kefuList[visitor.to_id]
if kefuConns != nil {
for _, kefuConn := range kefuConns {
kefuConn.WriteMessage(websocket.TextMessage, str)
}
}
sendPingOnlineUsers()
@ -92,13 +95,13 @@ func NewChatServer(c *gin.Context){
log.Println(err)
return
}
recevString=string(receive)
recevString = string(receive)
log.Println("客户端:", recevString)
message<-&Message{
conn:conn,
content: receive,
c:c,
messageType:messageType,
message <- &Message{
conn: conn,
content: receive,
c: c,
messageType: messageType,
}
}
}
@ -108,17 +111,18 @@ func SendKefuOnline(clientMsg ClientMessage, conn *websocket.Conn) {
sendMsg := TypeMessage{
Type: "kfOnline",
Data: ClientMessage{
Name: clientMsg.Name,
Avator: clientMsg.Avator,
Id: clientMsg.Id,
Group: clientMsg.Group,
Time: time.Now().Format("2006-01-02 15:04:05"),
Content: "客服上线",
Name: clientMsg.Name,
Avator: clientMsg.Avator,
Id: clientMsg.Id,
Group: clientMsg.Group,
Time: time.Now().Format("2006-01-02 15:04:05"),
Content: "客服上线",
},
}
jsonStrByte, _ := json.Marshal(sendMsg)
conn.WriteMessage(websocket.TextMessage,jsonStrByte)
conn.WriteMessage(websocket.TextMessage, jsonStrByte)
}
//发送通知
func SendNotice(msg string, conn *websocket.Conn) {
sendMsg := TypeMessage{
@ -126,7 +130,7 @@ func SendNotice(msg string, conn *websocket.Conn) {
Data: msg,
}
jsonStrByte, _ := json.Marshal(sendMsg)
conn.WriteMessage(websocket.TextMessage,jsonStrByte)
conn.WriteMessage(websocket.TextMessage, jsonStrByte)
}
//定时给客户端发送消息判断客户端是否在线
@ -138,28 +142,28 @@ func sendPingToClient() {
for {
str, _ := json.Marshal(msg)
for uid, user := range clientList {
err := user.conn.WriteMessage(websocket.TextMessage,str)
err := user.conn.WriteMessage(websocket.TextMessage, str)
if err != nil {
delete(clientList, uid)
models.UpdateVisitorStatus(uid,0)
models.UpdateVisitorStatus(uid, 0)
}
}
for kefuId, kfConns := range kefuList {
var newkfConns =make([]*websocket.Conn,0)
for _,kefuConn:=range kfConns{
if(kefuConn==nil){
var newkfConns = make([]*websocket.Conn, 0)
for _, kefuConn := range kfConns {
if kefuConn == nil {
continue
}
err:=kefuConn.WriteMessage(websocket.TextMessage,str)
err := kefuConn.WriteMessage(websocket.TextMessage, str)
if err == nil {
newkfConns=append(newkfConns,kefuConn)
newkfConns = append(newkfConns, kefuConn)
}
}
if newkfConns == nil {
delete(kefuList, kefuId)
}else{
kefuList[kefuId]=newkfConns
} else {
kefuList[kefuId] = newkfConns
}
}
time.Sleep(15 * time.Second)
@ -167,37 +171,39 @@ func sendPingToClient() {
}()
}
//定时给更新数据库状态
func sendPingUpdateStatus() {
for {
visitors:=models.FindVisitorsOnline()
for _,visitor :=range visitors{
_,ok:=clientList[visitor.VisitorId]
if !ok{
models.UpdateVisitorStatus(visitor.VisitorId,0)
visitors := models.FindVisitorsOnline()
for _, visitor := range visitors {
_, ok := clientList[visitor.VisitorId]
if !ok {
models.UpdateVisitorStatus(visitor.VisitorId, 0)
}
}
time.Sleep(20 * time.Second)
}
}
//定时推送当前在线用户
func sendPingOnlineUsers() {
var visitorIds []string
for visitorId, _ := range clientList {
visitorIds=append(visitorIds,visitorId)
visitorIds = append(visitorIds, visitorId)
}
sort.Strings(visitorIds)
for kefuId, kfConns := range kefuList {
result := make([]map[string]string, 0)
for _,visitorId:=range visitorIds{
user:=clientList[visitorId]
for _, visitorId := range visitorIds {
user := clientList[visitorId]
userInfo := make(map[string]string)
userInfo["uid"] = user.id
userInfo["username"] = user.name
userInfo["avator"] = user.avator
if user.to_id==kefuId{
if user.to_id == kefuId {
result = append(result, userInfo)
}
}
@ -206,31 +212,31 @@ func sendPingOnlineUsers() {
Data: result,
}
str, _ := json.Marshal(msg)
var newkfConns =make([]*websocket.Conn,0)
for _,kefuConn:=range kfConns{
err:=kefuConn.WriteMessage(websocket.TextMessage,str)
var newkfConns = make([]*websocket.Conn, 0)
for _, kefuConn := range kfConns {
err := kefuConn.WriteMessage(websocket.TextMessage, str)
if err == nil {
newkfConns=append(newkfConns,kefuConn)
newkfConns = append(newkfConns, kefuConn)
}
}
if len(newkfConns) == 0 {
delete(kefuList, kefuId)
}else{
kefuList[kefuId]=newkfConns
} else {
kefuList[kefuId] = newkfConns
}
}
}
//后端广播发送消息
func singleBroadcaster(){
func singleBroadcaster() {
for {
message:=<-message
message := <-message
//log.Println("debug:",message)
var typeMsg TypeMessage
var clientMsg ClientMessage
json.Unmarshal(message.content, &typeMsg)
conn:=message.conn
conn := message.conn
if typeMsg.Type == nil || typeMsg.Data == nil {
continue
}
@ -240,22 +246,22 @@ func singleBroadcaster(){
//用户上线
case "userInit":
json.Unmarshal(msgData, &clientMsg)
vistorInfo:=models.FindVisitorByVistorId(clientMsg.VisitorId)
if vistorInfo.VisitorId==""{
SendNotice("访客数据不存在",conn)
vistorInfo := models.FindVisitorByVistorId(clientMsg.VisitorId)
if vistorInfo.VisitorId == "" {
SendNotice("访客数据不存在", conn)
continue
}
//用户id对应的连接
user:=&vistor{
conn:conn,
name: clientMsg.Name,
user := &vistor{
conn: conn,
name: clientMsg.Name,
avator: clientMsg.Avator,
id:clientMsg.VisitorId,
to_id:clientMsg.ToId,
id: clientMsg.VisitorId,
to_id: clientMsg.ToId,
}
clientList[clientMsg.VisitorId] = user
//插入数据表
models.UpdateVisitor(clientMsg.VisitorId,1,clientMsg.ClientIp,message.c.ClientIP(),clientMsg.Refer)
models.UpdateVisitor(clientMsg.VisitorId, 1, clientMsg.ClientIp, message.c.ClientIP(), clientMsg.Refer)
//models.CreateVisitor(clientMsg.Name,clientMsg.Avator,message.c.ClientIP(),clientMsg.ToId,clientMsg.VisitorId,clientMsg.Refer,clientMsg.City,clientMsg.ClientIp)
userInfo := make(map[string]string)
userInfo["uid"] = user.id
@ -266,11 +272,11 @@ func singleBroadcaster(){
Data: userInfo,
}
str, _ := json.Marshal(msg)
kefuConns:=kefuList[user.to_id]
if kefuConns!=nil{
for k,kefuConn:=range kefuConns{
log.Println(k,"xxxxxxxx")
kefuConn.WriteMessage(websocket.TextMessage,str)
kefuConns := kefuList[user.to_id]
if kefuConns != nil {
for k, kefuConn := range kefuConns {
log.Println(k, "xxxxxxxx")
kefuConn.WriteMessage(websocket.TextMessage, str)
}
}
//客户上线发微信通知
@ -280,10 +286,10 @@ func singleBroadcaster(){
case "kfOnline":
json.Unmarshal(msgData, &clientMsg)
//客服id对应的连接
var newKefuConns =[]*websocket.Conn{conn}
kefuConns:=kefuList[clientMsg.Id]
if kefuConns!=nil{
newKefuConns=append(newKefuConns,kefuConns...)
var newKefuConns = []*websocket.Conn{conn}
kefuConns := kefuList[clientMsg.Id]
if kefuConns != nil {
newKefuConns = append(newKefuConns, kefuConns...)
}
log.Println(newKefuConns)
kefuList[clientMsg.Id] = newKefuConns
@ -295,8 +301,8 @@ func singleBroadcaster(){
//客服接手
case "kfConnect":
json.Unmarshal(msgData, &clientMsg)
visitor,ok := clientList[clientMsg.ToId]
if visitor==nil||!ok{
visitor, ok := clientList[clientMsg.ToId]
if visitor == nil || !ok {
continue
}
SendKefuOnline(clientMsg, visitor.conn)
@ -306,11 +312,8 @@ func singleBroadcaster(){
Type: "pong",
}
str, _ := json.Marshal(msg)
conn.WriteMessage(websocket.TextMessage,str)
conn.WriteMessage(websocket.TextMessage, str)
}
}
}

@ -13,6 +13,7 @@ import (
)
const PageSize = 20
func GetFolders(c *gin.Context) {
fid := c.Query("fid")
currentPage, _ := strconv.Atoi(c.Query("page"))
@ -44,9 +45,9 @@ func GetFolders(c *gin.Context) {
result["fid"] = fid
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":result,
"code": 200,
"msg": "ok",
"result": result,
})
}
func GetFolderList(c *gin.Context) {
@ -64,11 +65,12 @@ func GetFolderList(c *gin.Context) {
result["fid"] = fid
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":result,
"code": 200,
"msg": "ok",
"result": result,
})
}
//输出列表
func ActionFolder(w http.ResponseWriter, r *http.Request) {
fid := tools.GetUrlArg(r, "fid")

@ -5,9 +5,11 @@ import (
"github.com/taoshihan1991/imaptool/tools"
"net/http"
)
func Index(c *gin.Context) {
c.Redirect(302,"/index")
c.Redirect(302, "/index")
}
//首页跳转
func ActionIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.RequestURI() == "/favicon.ico" {

@ -9,7 +9,7 @@ import (
func PostIpblack(c *gin.Context) {
ip := c.PostForm("ip")
if ip==""{
if ip == "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "请输入IP!",
@ -17,7 +17,7 @@ func PostIpblack(c *gin.Context) {
return
}
kefuId, _ := c.Get("kefu_name")
models.CreateIpblack(ip,kefuId.(string))
models.CreateIpblack(ip, kefuId.(string))
c.JSON(200, gin.H{
"code": 200,
"msg": "添加黑名单成功!",
@ -25,7 +25,7 @@ func PostIpblack(c *gin.Context) {
}
func DelIpblack(c *gin.Context) {
ip := c.Query("ip")
if ip==""{
if ip == "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "请输入IP!",
@ -39,19 +39,19 @@ func DelIpblack(c *gin.Context) {
})
}
func GetIpblacks(c *gin.Context) {
page,_:=strconv.Atoi(c.Query("page"))
if page==0{
page=1
page, _ := strconv.Atoi(c.Query("page"))
if page == 0 {
page = 1
}
count:=models.CountIps(nil,nil)
list:=models.FindIps(nil,nil,uint(page),config.VisitorPageSize)
count := models.CountIps(nil, nil)
list := models.FindIps(nil, nil, uint(page), config.VisitorPageSize)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":gin.H{
"list":list,
"count":count,
"pagesize":config.PageSize,
"result": gin.H{
"list": list,
"count": count,
"pagesize": config.PageSize,
},
})
}
}

@ -7,36 +7,36 @@ import (
"strconv"
)
func GetKefuInfo(c *gin.Context){
kefuId, _ := c.Get("kefu_id")
user:=models.FindUserById(kefuId)
info:=make(map[string]interface{})
info["name"]=user.Nickname
info["id"]=user.Name
info["avator"]=user.Avator
func GetKefuInfo(c *gin.Context) {
kefuId, _ := c.Get("kefu_id")
user := models.FindUserById(kefuId)
info := make(map[string]interface{})
info["name"] = user.Nickname
info["id"] = user.Name
info["avator"] = user.Avator
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":info,
"code": 200,
"msg": "ok",
"result": info,
})
}
func GetKefuInfoSetting(c *gin.Context){
func GetKefuInfoSetting(c *gin.Context) {
kefuId := c.Query("kefu_id")
user:=models.FindUserById(kefuId)
user := models.FindUserById(kefuId)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":user,
"code": 200,
"msg": "ok",
"result": user,
})
}
func PostKefuInfo(c *gin.Context){
id:=c.PostForm("id")
name:=c.PostForm("name")
password:=c.PostForm("password")
avator:=c.PostForm("avator")
nickname:=c.PostForm("nickname")
roleId:=c.PostForm("role_id")
if roleId==""{
func PostKefuInfo(c *gin.Context) {
id := c.PostForm("id")
name := c.PostForm("name")
password := c.PostForm("password")
avator := c.PostForm("avator")
nickname := c.PostForm("nickname")
roleId := c.PostForm("role_id")
if roleId == "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "请选择角色!",
@ -44,51 +44,51 @@ func PostKefuInfo(c *gin.Context){
return
}
//插入新用户
if id==""{
uid:=models.CreateUser(name,tools.Md5(password),avator,nickname)
if uid==0{
if id == "" {
uid := models.CreateUser(name, tools.Md5(password), avator, nickname)
if uid == 0 {
c.JSON(200, gin.H{
"code": 400,
"msg": "增加用户失败",
"result":"",
"code": 400,
"msg": "增加用户失败",
"result": "",
})
return
}
roleIdInt,_:=strconv.Atoi(roleId)
models.CreateUserRole(uid,uint(roleIdInt))
}else{
roleIdInt, _ := strconv.Atoi(roleId)
models.CreateUserRole(uid, uint(roleIdInt))
} else {
//更新用户
if password!=""{
password=tools.Md5(password)
if password != "" {
password = tools.Md5(password)
}
models.UpdateUser(id,name,password,avator,nickname)
roleIdInt,_:=strconv.Atoi(roleId)
uid,_:=strconv.Atoi(id)
models.UpdateUser(id, name, password, avator, nickname)
roleIdInt, _ := strconv.Atoi(roleId)
uid, _ := strconv.Atoi(id)
models.DeleteRoleByUserId(uid)
models.CreateUserRole(uint(uid),uint(roleIdInt))
models.CreateUserRole(uint(uid), uint(roleIdInt))
}
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":"",
"code": 200,
"msg": "ok",
"result": "",
})
}
func GetKefuList(c *gin.Context){
users:=models.FindUsers()
func GetKefuList(c *gin.Context) {
users := models.FindUsers()
c.JSON(200, gin.H{
"code": 200,
"msg": "获取成功",
"result":users,
"code": 200,
"msg": "获取成功",
"result": users,
})
}
func DeleteKefuInfo(c *gin.Context){
func DeleteKefuInfo(c *gin.Context) {
kefuId := c.Query("id")
models.DeleteUserById(kefuId)
models.DeleteRoleByUserId(kefuId)
c.JSON(200, gin.H{
"code": 200,
"msg": "删除成功",
"result":"",
"code": 200,
"msg": "删除成功",
"result": "",
})
}

@ -5,6 +5,7 @@ import (
"github.com/taoshihan1991/imaptool/tools"
"time"
)
// @Summary 登陆验证接口
// @Produce json
// @Accept multipart/form-data
@ -19,35 +20,35 @@ func LoginCheckPass(c *gin.Context) {
password := c.PostForm("password")
username := c.PostForm("username")
info,uRole,ok:=CheckKefuPass(username, password)
userinfo:= make(map[string]interface{})
if !ok{
c.JSON(200, gin.H{
"code": 400,
"msg": "验证失败",
})
return
}
userinfo["name"] = info.Name
userinfo["kefu_id"] = info.ID
userinfo["type"] = "kefu"
if uRole.RoleId!=0 {
userinfo["role_id"] =uRole.RoleId
}else{
userinfo["role_id"]=2
}
userinfo["create_time"] = time.Now().Unix()
token, _ := tools.MakeToken(userinfo)
userinfo["ref_token"]=true
refToken, _ := tools.MakeToken(userinfo)
info, uRole, ok := CheckKefuPass(username, password)
userinfo := make(map[string]interface{})
if !ok {
c.JSON(200, gin.H{
"code": 200,
"msg": "验证成功,正在跳转",
"result": gin.H{
"token": token,
"ref_token":refToken,
"create_time":userinfo["create_time"],
},
"code": 400,
"msg": "验证失败",
})
return
}
userinfo["name"] = info.Name
userinfo["kefu_id"] = info.ID
userinfo["type"] = "kefu"
if uRole.RoleId != 0 {
userinfo["role_id"] = uRole.RoleId
} else {
userinfo["role_id"] = 2
}
userinfo["create_time"] = time.Now().Unix()
token, _ := tools.MakeToken(userinfo)
userinfo["ref_token"] = true
refToken, _ := tools.MakeToken(userinfo)
c.JSON(200, gin.H{
"code": 200,
"msg": "验证成功,正在跳转",
"result": gin.H{
"token": token,
"ref_token": refToken,
"create_time": userinfo["create_time"],
},
})
}

@ -19,29 +19,29 @@ func ActionMain(w http.ResponseWriter, r *http.Request) {
render.Display("main", render)
}
func MainCheckAuth(c *gin.Context) {
id,_:=c.Get("kefu_id")
userinfo:=models.FindUserRole("user.avator,user.name,user.id, role.name role_name",id)
id, _ := c.Get("kefu_id")
userinfo := models.FindUserRole("user.avator,user.name,user.id, role.name role_name", id)
c.JSON(200, gin.H{
"code": 200,
"msg": "验证成功",
"result":gin.H{
"avator":userinfo.Avator,
"name":userinfo.Name,
"role_name":userinfo.RoleName,
"result": gin.H{
"avator": userinfo.Avator,
"name": userinfo.Name,
"role_name": userinfo.RoleName,
},
})
}
func GetStatistics(c *gin.Context) {
visitors:=models.CountVisitors()
message:=models.CountMessage()
session:=len(clientList)
visitors := models.CountVisitors()
message := models.CountMessage()
session := len(clientList)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":gin.H{
"visitors":visitors,
"message":message,
"session":session,
"result": gin.H{
"visitors": visitors,
"message": message,
"session": session,
},
})
}

@ -13,6 +13,7 @@ import (
"strings"
"time"
)
// @Summary 发送消息接口
// @Produce json
// @Accept multipart/form-data
@ -28,7 +29,7 @@ func SendMessage(c *gin.Context) {
toId := c.PostForm("to_id")
content := c.PostForm("content")
cType := c.PostForm("type")
if content==""{
if content == "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "内容不能为空",
@ -38,26 +39,26 @@ func SendMessage(c *gin.Context) {
var kefuInfo models.User
var vistorInfo models.Visitor
if cType=="kefu"{
kefuInfo=models.FindUser(fromId)
vistorInfo=models.FindVisitorByVistorId(toId)
}else if cType=="visitor"{
vistorInfo=models.FindVisitorByVistorId(fromId)
kefuInfo=models.FindUser(toId)
if cType == "kefu" {
kefuInfo = models.FindUser(fromId)
vistorInfo = models.FindVisitorByVistorId(toId)
} else if cType == "visitor" {
vistorInfo = models.FindVisitorByVistorId(fromId)
kefuInfo = models.FindUser(toId)
}
if kefuInfo.ID==0 ||vistorInfo.ID==0{
if kefuInfo.ID == 0 || vistorInfo.ID == 0 {
c.JSON(200, gin.H{
"code": 400,
"msg": "用户不存在",
})
return
}
models.CreateMessage(kefuInfo.Name,vistorInfo.VisitorId,content,cType)
models.CreateMessage(kefuInfo.Name, vistorInfo.VisitorId, content, cType)
if cType=="kefu"{
guest,ok:=clientList[vistorInfo.VisitorId]
if guest==nil||!ok{
if cType == "kefu" {
guest, ok := clientList[vistorInfo.VisitorId]
if guest == nil || !ok {
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
@ -69,21 +70,21 @@ func SendMessage(c *gin.Context) {
msg := TypeMessage{
Type: "message",
Data: ClientMessage{
Name: kefuInfo.Nickname,
Avator: kefuInfo.Avator,
Id: kefuInfo.Name,
Time: time.Now().Format("2006-01-02 15:04:05"),
ToId: vistorInfo.VisitorId,
Content: content,
Name: kefuInfo.Nickname,
Avator: kefuInfo.Avator,
Id: kefuInfo.Name,
Time: time.Now().Format("2006-01-02 15:04:05"),
ToId: vistorInfo.VisitorId,
Content: content,
},
}
str, _ := json.Marshal(msg)
PushServerTcp(str)
conn.WriteMessage(websocket.TextMessage,str)
conn.WriteMessage(websocket.TextMessage, str)
}
if cType=="visitor"{
kefuConns,ok := kefuList[kefuInfo.Name]
if kefuConns==nil||!ok{
if cType == "visitor" {
kefuConns, ok := kefuList[kefuInfo.Name]
if kefuConns == nil || !ok {
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
@ -93,18 +94,18 @@ func SendMessage(c *gin.Context) {
msg := TypeMessage{
Type: "message",
Data: ClientMessage{
Avator: vistorInfo.Avator,
Id: vistorInfo.VisitorId,
Name: vistorInfo.Name,
ToId: kefuInfo.Name,
Content: content,
Time: time.Now().Format("2006-01-02 15:04:05"),
Avator: vistorInfo.Avator,
Id: vistorInfo.VisitorId,
Name: vistorInfo.Name,
ToId: kefuInfo.Name,
Content: content,
Time: time.Now().Format("2006-01-02 15:04:05"),
},
}
str, _ := json.Marshal(msg)
PushServerTcp(str)
for _,kefuConn:=range kefuConns{
kefuConn.WriteMessage(websocket.TextMessage,str)
for _, kefuConn := range kefuConns {
kefuConn.WriteMessage(websocket.TextMessage, str)
}
}
c.JSON(200, gin.H{
@ -114,7 +115,7 @@ func SendMessage(c *gin.Context) {
}
func SendVisitorNotice(c *gin.Context) {
notice := c.Query("msg")
if notice==""{
if notice == "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "msg不能为空",
@ -126,16 +127,16 @@ func SendVisitorNotice(c *gin.Context) {
Data: notice,
}
str, _ := json.Marshal(msg)
for _,visitor :=range clientList{
visitor.conn.WriteMessage(websocket.TextMessage,str)
for _, visitor := range clientList {
visitor.conn.WriteMessage(websocket.TextMessage, str)
}
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
})
}
func UploadImg(c *gin.Context){
config:=config.CreateConfig()
func UploadImg(c *gin.Context) {
config := config.CreateConfig()
f, err := c.FormFile("imgfile")
if err != nil {
c.JSON(200, gin.H{
@ -145,27 +146,27 @@ func UploadImg(c *gin.Context){
return
} else {
fileExt:=strings.ToLower(path.Ext(f.Filename))
if fileExt!=".png"&&fileExt!=".jpg"&&fileExt!=".gif"&&fileExt!=".jpeg"{
fileExt := strings.ToLower(path.Ext(f.Filename))
if fileExt != ".png" && fileExt != ".jpg" && fileExt != ".gif" && fileExt != ".jpeg" {
c.JSON(200, gin.H{
"code": 400,
"msg": "上传失败!只允许png,jpg,gif,jpeg文件",
})
return
}
fileName:=tools.Md5(fmt.Sprintf("%s%s",f.Filename,time.Now().String()))
fildDir:=fmt.Sprintf("%s%d%s/",config.Upload,time.Now().Year(),time.Now().Month().String())
isExist,_:=tools.IsFileExist(fildDir)
if !isExist{
os.Mkdir(fildDir,os.ModePerm)
fileName := tools.Md5(fmt.Sprintf("%s%s", f.Filename, time.Now().String()))
fildDir := fmt.Sprintf("%s%d%s/", config.Upload, time.Now().Year(), time.Now().Month().String())
isExist, _ := tools.IsFileExist(fildDir)
if !isExist {
os.Mkdir(fildDir, os.ModePerm)
}
filepath:=fmt.Sprintf("%s%s%s",fildDir,fileName,fileExt)
filepath := fmt.Sprintf("%s%s%s", fildDir, fileName, fileExt)
c.SaveUploadedFile(f, filepath)
c.JSON(200, gin.H{
"code": 200,
"msg": "上传成功!",
"result":gin.H{
"path":filepath,
"result": gin.H{
"path": filepath,
},
})
}

@ -8,29 +8,30 @@ import (
"github.com/taoshihan1991/imaptool/tools"
"os"
)
func MysqlGetConf(c *gin.Context) {
mysqlInfo:=config.GetMysql()
mysqlInfo := config.GetMysql()
c.JSON(200, gin.H{
"code": 200,
"msg": "验证成功",
"result":mysqlInfo,
"code": 200,
"msg": "验证成功",
"result": mysqlInfo,
})
}
func MysqlSetConf(c *gin.Context) {
mysqlServer:=c.PostForm("server")
mysqlPort:=c.PostForm("port")
mysqlDb:=c.PostForm("database")
mysqlUsername:=c.PostForm("username")
mysqlPassword:=c.PostForm("password")
dsn:=fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", mysqlUsername,mysqlPassword, mysqlServer, mysqlPort, mysqlDb)
mysql:=database.NewMysql()
mysql.Dsn=dsn
err:=mysql.Ping()
if err!=nil{
mysqlServer := c.PostForm("server")
mysqlPort := c.PostForm("port")
mysqlDb := c.PostForm("database")
mysqlUsername := c.PostForm("username")
mysqlPassword := c.PostForm("password")
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8", mysqlUsername, mysqlPassword, mysqlServer, mysqlPort, mysqlDb)
mysql := database.NewMysql()
mysql.Dsn = dsn
err := mysql.Ping()
if err != nil {
c.JSON(200, gin.H{
"code": 403,
"msg": "数据库连接失败:"+err.Error(),
"msg": "数据库连接失败:" + err.Error(),
})
return
}
@ -49,11 +50,11 @@ func MysqlSetConf(c *gin.Context) {
"Password":"%s"
}
`
data := fmt.Sprintf(format, mysqlServer,mysqlPort,mysqlDb,mysqlUsername,mysqlPassword)
data := fmt.Sprintf(format, mysqlServer, mysqlPort, mysqlDb, mysqlUsername, mysqlPassword)
file.WriteString(data)
c.JSON(200, gin.H{
"code": 200,
"msg": "操作成功",
})
}
}

@ -11,56 +11,58 @@ import (
"net/http"
"time"
)
func GetNotice(c *gin.Context) {
kefuId:=c.Query("kefu_id")
welcomes:=models.FindWelcomesByUserId(kefuId)
user:=models.FindUser(kefuId)
result:=make([]gin.H,0)
for _,welcome:=range welcomes{
h:=gin.H{
"name":user.Nickname,
"avator":user.Avator,
"is_kefu":false,
"content":welcome.Content,
"time":time.Now().Format("2006-01-02 15:04:05"),
kefuId := c.Query("kefu_id")
welcomes := models.FindWelcomesByUserId(kefuId)
user := models.FindUser(kefuId)
result := make([]gin.H, 0)
for _, welcome := range welcomes {
h := gin.H{
"name": user.Nickname,
"avator": user.Avator,
"is_kefu": false,
"content": welcome.Content,
"time": time.Now().Format("2006-01-02 15:04:05"),
}
result=append(result,h)
result = append(result, h)
}
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":result,
"code": 200,
"msg": "ok",
"result": result,
})
}
func GetNotices(c *gin.Context) {
kefuId,_:=c.Get("kefu_name")
welcomes:=models.FindWelcomesByUserId(kefuId)
kefuId, _ := c.Get("kefu_name")
welcomes := models.FindWelcomesByUserId(kefuId)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":welcomes,
"code": 200,
"msg": "ok",
"result": welcomes,
})
}
func PostNotice(c *gin.Context) {
kefuId,_:=c.Get("kefu_name")
content:=c.PostForm("content")
models.CreateWelcome(fmt.Sprintf("%s",kefuId),content)
kefuId, _ := c.Get("kefu_name")
content := c.PostForm("content")
models.CreateWelcome(fmt.Sprintf("%s", kefuId), content)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":"",
"code": 200,
"msg": "ok",
"result": "",
})
}
func DelNotice(c *gin.Context) {
kefuId,_:=c.Get("kefu_name")
id:=c.Query("id")
models.DeleteWelcome(kefuId,id)
kefuId, _ := c.Get("kefu_name")
id := c.Query("id")
models.DeleteWelcome(kefuId, id)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":"",
"code": 200,
"msg": "ok",
"result": "",
})
}
var upgrader = websocket.Upgrader{}
var oldFolders map[string]int

@ -1,6 +1,7 @@
package controller
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Code int `json:"code"`
Msg string `json:"msg"`
result interface{} `json:"result"`
}

@ -5,27 +5,27 @@ import (
"github.com/taoshihan1991/imaptool/models"
)
func GetRoleList(c *gin.Context){
roles:=models.FindRoles()
func GetRoleList(c *gin.Context) {
roles := models.FindRoles()
c.JSON(200, gin.H{
"code": 200,
"msg": "获取成功",
"result":roles,
"code": 200,
"msg": "获取成功",
"result": roles,
})
}
func PostRole(c *gin.Context){
roleId:=c.PostForm("id")
method:=c.PostForm("method")
name:=c.PostForm("name")
path:=c.PostForm("path")
if roleId==""||method==""||name==""||path==""{
func PostRole(c *gin.Context) {
roleId := c.PostForm("id")
method := c.PostForm("method")
name := c.PostForm("name")
path := c.PostForm("path")
if roleId == "" || method == "" || name == "" || path == "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "参数不能为空",
})
return
}
models.SaveRole(roleId,name,method,path)
models.SaveRole(roleId, name, method, path)
c.JSON(200, gin.H{
"code": 200,
"msg": "修改成功",

@ -6,28 +6,28 @@ import (
)
func GetConfigs(c *gin.Context) {
configs:=models.FindConfigs()
configs := models.FindConfigs()
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":configs,
"code": 200,
"msg": "ok",
"result": configs,
})
}
func PostConfig(c *gin.Context){
key:=c.PostForm("key")
value:=c.PostForm("value")
if key==""||value==""{
func PostConfig(c *gin.Context) {
key := c.PostForm("key")
value := c.PostForm("value")
if key == "" || value == "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "error",
})
return
}
models.UpdateConfig(key,value)
models.UpdateConfig(key, value)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":"",
"code": 200,
"msg": "ok",
"result": "",
})
}
}

@ -8,17 +8,17 @@ import (
"strconv"
)
func SendServerJiang(content string)string{
noticeServerJiang,err:=strconv.ParseBool(models.FindConfig("NoticeServerJiang"))
serverJiangAPI:=models.FindConfig("ServerJiangAPI")
if err!=nil || !noticeServerJiang || serverJiangAPI==""{
log.Println("do not notice serverjiang:",serverJiangAPI,noticeServerJiang)
func SendServerJiang(content string) string {
noticeServerJiang, err := strconv.ParseBool(models.FindConfig("NoticeServerJiang"))
serverJiangAPI := models.FindConfig("ServerJiangAPI")
if err != nil || !noticeServerJiang || serverJiangAPI == "" {
log.Println("do not notice serverjiang:", serverJiangAPI, noticeServerJiang)
return ""
}
sendStr:=fmt.Sprintf("%s,访客来了",content)
desp:="[登录](https://gofly.sopans.com/main)";
url:=serverJiangAPI+"?text="+sendStr+"&desp="+desp
sendStr := fmt.Sprintf("%s,访客来了", content)
desp := "[登录](https://gofly.sopans.com/main)"
url := serverJiangAPI + "?text=" + sendStr + "&desp=" + desp
//log.Println(url)
res:=tools.Get(url)
res := tools.Get(url)
return res
}

@ -5,8 +5,10 @@ import (
"log"
"net"
)
var clientTcpList = make(map[string]net.Conn)
func NewTcpServer(tcpBaseServer string){
func NewTcpServer(tcpBaseServer string) {
listener, err := net.Listen("tcp", tcpBaseServer)
if err != nil {
log.Println("Error listening", err.Error())
@ -20,37 +22,37 @@ func NewTcpServer(tcpBaseServer string){
return // 终止程序
}
var remoteIpAddress = conn.RemoteAddr()
clientTcpList[remoteIpAddress.String()]=conn
log.Println(remoteIpAddress,clientTcpList)
clientTcpList[remoteIpAddress.String()] = conn
log.Println(remoteIpAddress, clientTcpList)
//clientTcpList=append(clientTcpList,conn)
}
}
func PushServerTcp(str []byte){
for ip,conn:=range clientTcpList{
line:=append(str,[]byte("\r\n")...)
_,err:=conn.Write(line)
log.Println(ip,err)
if err!=nil{
func PushServerTcp(str []byte) {
for ip, conn := range clientTcpList {
line := append(str, []byte("\r\n")...)
_, err := conn.Write(line)
log.Println(ip, err)
if err != nil {
conn.Close()
delete(clientTcpList,ip)
delete(clientTcpList, ip)
//clientTcpList=append(clientTcpList[:index],clientTcpList[index+1:]...)
}
}
}
func DeleteOnlineTcp(c *gin.Context) {
ip:=c.Query("ip")
for ipkey,conn :=range clientTcpList{
if ip==ipkey{
ip := c.Query("ip")
for ipkey, conn := range clientTcpList {
if ip == ipkey {
conn.Close()
delete(clientTcpList,ip)
delete(clientTcpList, ip)
}
if ip=="all"{
if ip == "all" {
conn.Close()
delete(clientTcpList,ipkey)
delete(clientTcpList, ipkey)
}
}
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
})
}
}

@ -12,6 +12,7 @@ import (
"math/rand"
"strconv"
)
func PostVisitor(c *gin.Context) {
name := c.PostForm("name")
avator := c.PostForm("avator")
@ -20,22 +21,22 @@ func PostVisitor(c *gin.Context) {
refer := c.PostForm("refer")
city := c.PostForm("city")
client_ip := c.PostForm("client_ip")
if name==""||avator==""||toId==""||id==""||refer==""||city==""||client_ip==""{
if name == "" || avator == "" || toId == "" || id == "" || refer == "" || city == "" || client_ip == "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "error",
})
return
}
kefuInfo:=models.FindUser(toId)
if kefuInfo.ID==0{
kefuInfo := models.FindUser(toId)
if kefuInfo.ID == 0 {
c.JSON(200, gin.H{
"code": 400,
"msg": "用户不存在",
})
return
}
models.CreateVisitor(name,avator,c.ClientIP(),toId,id,refer,city,client_ip)
models.CreateVisitor(name, avator, c.ClientIP(), toId, id, refer, city, client_ip)
userInfo := make(map[string]string)
userInfo["uid"] = id
@ -46,11 +47,11 @@ func PostVisitor(c *gin.Context) {
Data: userInfo,
}
str, _ := json.Marshal(msg)
kefuConns:=kefuList[toId]
if kefuConns!=nil{
for k,kefuConn:=range kefuConns{
log.Println(k,"xxxxxxxx")
kefuConn.WriteMessage(websocket.TextMessage,str)
kefuConns := kefuList[toId]
if kefuConns != nil {
for k, kefuConn := range kefuConns {
log.Println(k, "xxxxxxxx")
kefuConn.WriteMessage(websocket.TextMessage, str)
}
}
c.JSON(200, gin.H{
@ -59,11 +60,11 @@ func PostVisitor(c *gin.Context) {
})
}
func PostVisitorLogin(c *gin.Context) {
ipcity:=tools.ParseIp(c.ClientIP())
avator := fmt.Sprintf("/static/images/%d.jpg",rand.Intn(14))
ipcity := tools.ParseIp(c.ClientIP())
avator := fmt.Sprintf("/static/images/%d.jpg", rand.Intn(14))
toId := c.PostForm("to_id")
id := c.PostForm("id")
if id==""{
if id == "" {
id = tools.Uuid()
}
refer := c.PostForm("refer")
@ -71,47 +72,48 @@ func PostVisitorLogin(c *gin.Context) {
city string
name string
)
if ipcity!=nil{
city = ipcity.CountryName+ipcity.RegionName+ipcity.CityName
name=ipcity.CountryName+ipcity.RegionName+ipcity.CityName+"网友"
}else{
city="未识别地区"
name="匿名网友"
if ipcity != nil {
city = ipcity.CountryName + ipcity.RegionName + ipcity.CityName
name = ipcity.CountryName + ipcity.RegionName + ipcity.CityName + "网友"
} else {
city = "未识别地区"
name = "匿名网友"
}
client_ip := c.PostForm("client_ip")
//log.Println(name,avator,c.ClientIP(),toId,id,refer,city,client_ip)
if name==""||avator==""||toId==""||id==""||refer==""||city==""||client_ip==""{
if name == "" || avator == "" || toId == "" || id == "" || refer == "" || city == "" || client_ip == "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "error",
})
return
}
kefuInfo:=models.FindUser(toId)
if kefuInfo.ID==0{
kefuInfo := models.FindUser(toId)
if kefuInfo.ID == 0 {
c.JSON(200, gin.H{
"code": 400,
"msg": "客服不存在",
})
return
}
models.CreateVisitor(name,avator,c.ClientIP(),toId,id,refer,city,client_ip)
visitor:=models.FindVisitorByVistorId(id)
models.CreateVisitor(name, avator, c.ClientIP(), toId, id, refer, city, client_ip)
visitor := models.FindVisitorByVistorId(id)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":visitor,
"code": 200,
"msg": "ok",
"result": visitor,
})
}
func GetVisitor(c *gin.Context) {
visitorId:=c.Query("visitorId")
vistor:=models.FindVisitorByVistorId(visitorId)
visitorId := c.Query("visitorId")
vistor := models.FindVisitorByVistorId(visitorId)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":vistor,
"code": 200,
"msg": "ok",
"result": vistor,
})
}
// @Summary 获取访客列表接口
// @Produce json
// @Accept multipart/form-data
@ -121,20 +123,21 @@ func GetVisitor(c *gin.Context) {
// @Failure 200 {object} controller.Response
// @Router /visitors [get]
func GetVisitors(c *gin.Context) {
page,_:=strconv.Atoi(c.Query("page"))
kefuId,_:=c.Get("kefu_name")
vistors:=models.FindVisitorsByKefuId(uint(page),config.VisitorPageSize,kefuId.(string))
count:=models.CountVisitorsByKefuId(kefuId.(string))
page, _ := strconv.Atoi(c.Query("page"))
kefuId, _ := c.Get("kefu_name")
vistors := models.FindVisitorsByKefuId(uint(page), config.VisitorPageSize, kefuId.(string))
count := models.CountVisitorsByKefuId(kefuId.(string))
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":gin.H{
"list":vistors,
"count":count,
"pagesize":config.PageSize,
"result": gin.H{
"list": vistors,
"count": count,
"pagesize": config.PageSize,
},
})
}
// @Summary 获取访客聊天信息接口
// @Produce json
// @Accept multipart/form-data
@ -144,53 +147,53 @@ func GetVisitors(c *gin.Context) {
// @Failure 200 {object} controller.Response
// @Router /messages [get]
func GetVisitorMessage(c *gin.Context) {
visitorId:=c.Query("visitorId")
messages:=models.FindMessageByVisitorId(visitorId)
result:=make([]map[string]interface{},0)
for _,message:=range messages{
item:=make(map[string]interface{})
visitorId := c.Query("visitorId")
messages := models.FindMessageByVisitorId(visitorId)
result := make([]map[string]interface{}, 0)
for _, message := range messages {
item := make(map[string]interface{})
var visitor models.Visitor
var kefu models.User
if visitor.Name=="" || kefu.Name==""{
kefu=models.FindUser(message.KefuId)
visitor=models.FindVisitorByVistorId(message.VisitorId)
if visitor.Name == "" || kefu.Name == "" {
kefu = models.FindUser(message.KefuId)
visitor = models.FindVisitorByVistorId(message.VisitorId)
}
item["time"]=message.CreatedAt.Format("2006-01-02 15:04:05")
item["content"]=message.Content
item["mes_type"]=message.MesType
item["visitor_name"]=visitor.Name
item["visitor_avator"]=visitor.Avator
item["kefu_name"]=kefu.Nickname
item["kefu_avator"]=kefu.Avator
result=append(result,item)
item["time"] = message.CreatedAt.Format("2006-01-02 15:04:05")
item["content"] = message.Content
item["mes_type"] = message.MesType
item["visitor_name"] = visitor.Name
item["visitor_avator"] = visitor.Avator
item["kefu_name"] = kefu.Nickname
item["kefu_avator"] = kefu.Avator
result = append(result, item)
}
models.ReadMessageByVisitorId(visitorId)
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":result,
"code": 200,
"msg": "ok",
"result": result,
})
}
func GetVisitorOnlines(c *gin.Context) {
users:=make([]map[string]string,0)
for uid,visitor :=range clientList{
users := make([]map[string]string, 0)
for uid, visitor := range clientList {
userInfo := make(map[string]string)
userInfo["uid"] = uid
userInfo["name"] = visitor.name
userInfo["avator"] = visitor.avator
users=append(users,userInfo)
users = append(users, userInfo)
}
tcps:=make([]string,0)
for ip,_ :=range clientTcpList{
tcps=append(tcps,ip)
tcps := make([]string, 0)
for ip, _ := range clientTcpList {
tcps = append(tcps, ip)
}
c.JSON(200, gin.H{
"code": 200,
"msg": "ok",
"result":gin.H{
"ws":users,
"tcp":tcps,
"result": gin.H{
"ws": users,
"tcp": tcps,
},
})
}
}

@ -9,14 +9,14 @@ import (
"sort"
)
func GetCheckWeixinSign(c *gin.Context){
token:=models.FindConfig("WeixinToken")
signature:=c.Query("signature")
timestamp:=c.Query("timestamp")
nonce:=c.Query("nonce")
echostr:=c.Query("echostr")
func GetCheckWeixinSign(c *gin.Context) {
token := models.FindConfig("WeixinToken")
signature := c.Query("signature")
timestamp := c.Query("timestamp")
nonce := c.Query("nonce")
echostr := c.Query("echostr")
//将token、timestamp、nonce三个参数进行字典序排序
var tempArray = []string{token, timestamp, nonce}
var tempArray = []string{token, timestamp, nonce}
sort.Strings(tempArray)
//将三个参数字符串拼接成一个字符串进行sha1加密
var sha1String string = ""

@ -6,20 +6,22 @@ import (
_ "github.com/go-sql-driver/mysql"
"github.com/taoshihan1991/imaptool/config"
)
type Mysql struct{
type Mysql struct {
SqlDB *sql.DB
Dsn string
Dsn string
}
func NewMysql()*Mysql{
mysql:=config.CreateMysql()
func NewMysql() *Mysql {
mysql := config.CreateMysql()
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", mysql.Username, mysql.Password, mysql.Server, mysql.Port, mysql.Database)
return &Mysql{
Dsn:dsn,
Dsn: dsn,
}
}
func (db *Mysql)Ping()error{
func (db *Mysql) Ping() error {
sqlDb, _ := sql.Open("mysql", db.Dsn)
db.SqlDB=sqlDb
db.SqlDB = sqlDb
return db.SqlDB.Ping()
}
}

@ -6,25 +6,26 @@ import (
"github.com/gin-gonic/gin"
"log"
)
func CasbinACL(c *gin.Context){
roleId, _ :=c.Get("role_id")
sub:=fmt.Sprintf("%s_%d","role",int(roleId.(float64)))
obj:=c.Request.RequestURI
act:=c.Request.Method
func CasbinACL(c *gin.Context) {
roleId, _ := c.Get("role_id")
sub := fmt.Sprintf("%s_%d", "role", int(roleId.(float64)))
obj := c.Request.RequestURI
act := c.Request.Method
e, err := casbin.NewEnforcer("config/model.conf", "config/policy.csv")
log.Println(sub,obj,act,err)
ok,err:=e.Enforce(sub,obj,act)
if err!=nil{
log.Println(sub, obj, act, err)
ok, err := e.Enforce(sub, obj, act)
if err != nil {
c.JSON(200, gin.H{
"code": 403,
"msg": "没有权限:"+err.Error(),
"msg": "没有权限:" + err.Error(),
})
c.Abort()
}
if !ok{
if !ok {
c.JSON(200, gin.H{
"code": 403,
"msg": fmt.Sprintf("没有权限:%s,%s,%s",sub,obj,act),
"msg": fmt.Sprintf("没有权限:%s,%s,%s", sub, obj, act),
})
c.Abort()
}

@ -5,10 +5,10 @@ import (
"github.com/taoshihan1991/imaptool/models"
)
func Ipblack(c *gin.Context){
ip:=c.ClientIP()
ipblack:=models.FindIp(ip)
if ipblack.IP!=""{
func Ipblack(c *gin.Context) {
ip := c.ClientIP()
ipblack := models.FindIp(ip)
if ipblack.IP != "" {
c.JSON(200, gin.H{
"code": 400,
"msg": "IP已被加入黑名单",

@ -5,7 +5,8 @@ import (
"github.com/taoshihan1991/imaptool/tools"
"time"
)
func JwtPageMiddleware(c *gin.Context){
func JwtPageMiddleware(c *gin.Context) {
//暂时不处理
//token := c.Query("token")
//userinfo := tools.ParseToken(token)
@ -14,10 +15,10 @@ func JwtPageMiddleware(c *gin.Context){
// c.Abort()
//}
}
func JwtApiMiddleware(c *gin.Context){
func JwtApiMiddleware(c *gin.Context) {
token := c.GetHeader("token")
userinfo := tools.ParseToken(token)
if userinfo == nil||userinfo["name"]==nil||userinfo["create_time"]==nil {
if userinfo == nil || userinfo["name"] == nil || userinfo["create_time"] == nil {
c.JSON(200, gin.H{
"code": 400,
"msg": "验证失败",
@ -25,21 +26,21 @@ func JwtApiMiddleware(c *gin.Context){
c.Abort()
return
}
createTime:=int64(userinfo["create_time"].(float64))
var expire int64=24*60*60
nowTime:=time.Now().Unix();
if (nowTime-createTime) >=expire{
createTime := int64(userinfo["create_time"].(float64))
var expire int64 = 24 * 60 * 60
nowTime := time.Now().Unix()
if (nowTime - createTime) >= expire {
c.JSON(200, gin.H{
"code": 401,
"msg": "token失效",
})
c.Abort()
}
c.Set("user",userinfo["name"])
c.Set("user", userinfo["name"])
//log.Println(userinfo)
//if userinfo["type"]=="kefu"{
c.Set("kefu_id",userinfo["kefu_id"])
c.Set("kefu_name",userinfo["name"])
c.Set("role_id",userinfo["role_id"])
c.Set("kefu_id", userinfo["kefu_id"])
c.Set("kefu_name", userinfo["name"])
c.Set("role_id", userinfo["role_id"])
//}
}

@ -4,11 +4,10 @@ import (
"github.com/gin-gonic/gin"
)
func SetLanguage(c *gin.Context){
func SetLanguage(c *gin.Context) {
lang := c.Query("lang")
if lang == "" ||lang!="cn"{
if lang == "" || lang != "cn" {
lang = "en"
}
c.Set("lang",lang)
c.Set("lang", lang)
}

@ -6,45 +6,44 @@ import (
"strings"
)
func RbacAuth(c *gin.Context){
roleId, _ :=c.Get("role_id")
role:=models.FindRole(roleId)
func RbacAuth(c *gin.Context) {
roleId, _ := c.Get("role_id")
role := models.FindRole(roleId)
var methodFlag bool
rPaths:=strings.Split(c.Request.RequestURI,"?")
if role.Method!="*"{
methods:=strings.Split(role.Method,",")
for _,m:=range methods{
if c.Request.Method==m{
methodFlag=true
rPaths := strings.Split(c.Request.RequestURI, "?")
if role.Method != "*" {
methods := strings.Split(role.Method, ",")
for _, m := range methods {
if c.Request.Method == m {
methodFlag = true
break
}
}
if !methodFlag{
if !methodFlag {
c.JSON(200, gin.H{
"code": 403,
"msg": "没有权限:"+c.Request.Method+","+rPaths[0],
"msg": "没有权限:" + c.Request.Method + "," + rPaths[0],
})
c.Abort()
return
}
}
var flag bool
if role.Path!="*"{
paths:=strings.Split(role.Path,",")
for _,p:=range paths{
if rPaths[0]==p{
flag=true
if role.Path != "*" {
paths := strings.Split(role.Path, ",")
for _, p := range paths {
if rPaths[0] == p {
flag = true
break
}
}
if !flag{
if !flag {
c.JSON(200, gin.H{
"code": 403,
"msg": "没有权限:"+rPaths[0],
"msg": "没有权限:" + rPaths[0],
})
c.Abort()
return
}
}
}

@ -1,31 +1,33 @@
package models
var CustomConfigs []Config
type Config struct{
ID uint `gorm:"primary_key" json:"id"`
ConfName string `json:"conf_name"`
ConfKey string `json:"conf_key"`
type Config struct {
ID uint `gorm:"primary_key" json:"id"`
ConfName string `json:"conf_name"`
ConfKey string `json:"conf_key"`
ConfValue string `json:"conf_value"`
}
func UpdateConfig(key string,value string){
c:=&Config{
func UpdateConfig(key string, value string) {
c := &Config{
ConfValue: value,
}
DB.Model(c).Where("conf_key = ?",key).Update(c)
DB.Model(c).Where("conf_key = ?", key).Update(c)
}
func FindConfigs()[]Config{
func FindConfigs() []Config {
var config []Config
DB.Find(&config)
return config
}
func InitConfig(){
CustomConfigs=FindConfigs()
func InitConfig() {
CustomConfigs = FindConfigs()
}
func FindConfig(key string)string{
for _,config:=range CustomConfigs{
if key==config.ConfKey{
func FindConfig(key string) string {
for _, config := range CustomConfigs {
if key == config.ConfKey {
return config.ConfValue
}
}
return ""
}
}

@ -2,49 +2,51 @@ package models
import "time"
type Ipblack struct{
ID uint `gorm:"primary_key" json:"id"`
IP string `json:"ip"`
KefuId string `json:"kefu_id"`
type Ipblack struct {
ID uint `gorm:"primary_key" json:"id"`
IP string `json:"ip"`
KefuId string `json:"kefu_id"`
CreateAt time.Time `json:"create_at"`
}
func CreateIpblack(ip string,kefuId string)uint{
black:=&Ipblack{
IP:ip,
KefuId: kefuId,
func CreateIpblack(ip string, kefuId string) uint {
black := &Ipblack{
IP: ip,
KefuId: kefuId,
CreateAt: time.Now(),
}
DB.Create(black)
return black.ID
}
func DeleteIpblackByIp(ip string){
DB.Where("ip = ?",ip).Delete(Ipblack{})
func DeleteIpblackByIp(ip string) {
DB.Where("ip = ?", ip).Delete(Ipblack{})
}
func FindIp(ip string)Ipblack{
func FindIp(ip string) Ipblack {
var ipblack Ipblack
DB.Where("ip = ?", ip).First(&ipblack)
return ipblack
}
func FindIps(query interface{},args []interface{},page uint,pagesize uint)[]Ipblack{
offset:=(page-1)*pagesize
if offset<0{
offset=0
func FindIps(query interface{}, args []interface{}, page uint, pagesize uint) []Ipblack {
offset := (page - 1) * pagesize
if offset < 0 {
offset = 0
}
var ipblacks []Ipblack
if query!=nil{
if query != nil {
DB.Where(query, args...).Offset(offset).Limit(pagesize).Find(&ipblacks)
}else{
} else {
DB.Offset(offset).Limit(pagesize).Find(&ipblacks)
}
return ipblacks
}
//查询条数
func CountIps(query interface{},args []interface{})uint{
func CountIps(query interface{}, args []interface{}) uint {
var count uint
if query!=nil{
DB.Model(&Visitor{}).Where(query,args...).Count(&count)
}else{
if query != nil {
DB.Model(&Visitor{}).Where(query, args...).Count(&count)
} else {
DB.Model(&Visitor{}).Count(&count)
}
return count
}
}

@ -1,43 +1,48 @@
package models
type Message struct {
Model
KefuId string `json:"kefu_id"`
KefuId string `json:"kefu_id"`
VisitorId string `json:"visitor_id"`
Content string `json:"content"`
MesType string `json:"mes_type"`
Status string `json:"status"`
Content string `json:"content"`
MesType string `json:"mes_type"`
Status string `json:"status"`
}
func CreateMessage(kefu_id string,visitor_id string,content string,mes_type string){
v:=&Message{
KefuId: kefu_id,
func CreateMessage(kefu_id string, visitor_id string, content string, mes_type string) {
v := &Message{
KefuId: kefu_id,
VisitorId: visitor_id,
Content: content,
MesType: mes_type,
MesType: mes_type,
Status: "unread",
}
DB.Create(v)
}
func FindMessageByVisitorId(visitor_id string)[]Message{
func FindMessageByVisitorId(visitor_id string) []Message {
var messages []Message
DB.Where("visitor_id=?",visitor_id).Order("id asc").Find(&messages)
DB.Where("visitor_id=?", visitor_id).Order("id asc").Find(&messages)
return messages
}
//修改消息状态
func ReadMessageByVisitorId(visitor_id string){
message:=&Message{
Status:"read",
func ReadMessageByVisitorId(visitor_id string) {
message := &Message{
Status: "read",
}
DB.Model(&message).Where("visitor_id=?",visitor_id).Update(message)
DB.Model(&message).Where("visitor_id=?", visitor_id).Update(message)
}
//获取未读数
func FindUnreadMessageNumByVisitorId(visitor_id string)uint{
func FindUnreadMessageNumByVisitorId(visitor_id string) uint {
var count uint
DB.Where("visitor_id=? and status=?",visitor_id,"unread").Count(&count)
DB.Where("visitor_id=? and status=?", visitor_id, "unread").Count(&count)
return count
}
//查询条数
func CountMessage()uint{
func CountMessage() uint {
var count uint
DB.Model(&Message{}).Count(&count)
return count
}
}

@ -6,19 +6,22 @@ import (
"github.com/taoshihan1991/imaptool/config"
"time"
)
var DB *gorm.DB
type Model struct {
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID uint `gorm:"primary_key" json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `sql:"index" json:"deleted_at"`
}
func init(){
mysql:=config.CreateMysql()
func init() {
mysql := config.CreateMysql()
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", mysql.Username, mysql.Password, mysql.Server, mysql.Port, mysql.Database)
var err error
DB,err=gorm.Open("mysql",dsn)
if err!=nil{
DB, err = gorm.Open("mysql", dsn)
if err != nil {
panic("数据库连接失败!")
}
DB.SingularTable(true)
@ -28,9 +31,9 @@ func init(){
InitConfig()
}
func Execute(sql string){
func Execute(sql string) {
DB.Exec(sql)
}
func CloseDB() {
defer DB.Close()
}
}

@ -1,25 +1,27 @@
package models
type Role struct{
Id string `json:"role_id"`
Name string `json:"role_name"`
type Role struct {
Id string `json:"role_id"`
Name string `json:"role_name"`
Method string `json:"method"`
Path string `json:"path"`
Path string `json:"path"`
}
func FindRoles()[]Role{
func FindRoles() []Role {
var roles []Role
DB.Order("id desc").Find(&roles)
return roles
}
func FindRole(id interface{})Role{
func FindRole(id interface{}) Role {
var role Role
DB.Where("id = ?", id).First(&role)
return role
}
func SaveRole(id string,name string,method string,path string){
role:=&Role{
func SaveRole(id string, name string, method string, path string) {
role := &Role{
Method: method,
Name: name,
Path: path,
Name: name,
Path: path,
}
DB.Model(role).Where("id=?",id).Update(role)
}
DB.Model(role).Where("id=?", id).Update(role)
}

@ -4,23 +4,24 @@ import (
"strconv"
)
type User_role struct{
ID uint `gorm:"primary_key" json:"id"`
type User_role struct {
ID uint `gorm:"primary_key" json:"id"`
UserId string `json:"user_id"`
RoleId uint `json:"role_id"`
RoleId uint `json:"role_id"`
}
func FindRoleByUserId(userId interface{})User_role{
func FindRoleByUserId(userId interface{}) User_role {
var uRole User_role
DB.Where("user_id = ?", userId).First(&uRole)
return uRole
}
func CreateUserRole(userId uint,roleId uint){
uRole:=&User_role{
UserId:strconv.Itoa(int(userId)),
func CreateUserRole(userId uint, roleId uint) {
uRole := &User_role{
UserId: strconv.Itoa(int(userId)),
RoleId: roleId,
}
DB.Create(uRole)
}
func DeleteRoleByUserId(userId interface{}){
func DeleteRoleByUserId(userId interface{}) {
DB.Where("user_id = ?", userId).Delete(User_role{})
}
}

@ -3,56 +3,58 @@ package models
import (
_ "github.com/jinzhu/gorm/dialects/mysql"
)
type User struct {
Model
Name string `json:"name"`
Name string `json:"name"`
Password string `json:"password"`
Nickname string `json:"nickname"`
Avator string `json:"avator"`
Avator string `json:"avator"`
RoleName string `json:"role_name" sql:"-"`
RoleId string `json:"role_id" sql:"-"`
RoleId string `json:"role_id" sql:"-"`
}
func CreateUser(name string,password string,avator string,nickname string)uint{
user:=&User{
Name:name,
func CreateUser(name string, password string, avator string, nickname string) uint {
user := &User{
Name: name,
Password: password,
Avator:avator,
Avator: avator,
Nickname: nickname,
}
DB.Create(user)
return user.ID
}
func UpdateUser(id string,name string,password string,avator string,nickname string){
user:=&User{
Name:name,
Avator:avator,
func UpdateUser(id string, name string, password string, avator string, nickname string) {
user := &User{
Name: name,
Avator: avator,
Nickname: nickname,
}
if password!=""{
user.Password=password
if password != "" {
user.Password = password
}
DB.Model(&User{}).Where("id = ?",id).Update(user)
DB.Model(&User{}).Where("id = ?", id).Update(user)
}
func FindUser(username string)User{
func FindUser(username string) User {
var user User
DB.Where("name = ?", username).First(&user)
return user
}
func FindUserById(id interface{})User{
func FindUserById(id interface{}) User {
var user User
DB.Select("user.*,role.name role_name,role.id role_id").Joins("join user_role on user.id=user_role.user_id").Joins("join role on user_role.role_id=role.id").Where("user.id = ?", id).First(&user)
return user
}
func DeleteUserById(id string){
DB.Where("id = ?",id).Delete(User{})
func DeleteUserById(id string) {
DB.Where("id = ?", id).Delete(User{})
}
func FindUsers()[]User{
func FindUsers() []User {
var users []User
DB.Select("user.*,role.name role_name").Joins("left join user_role on user.id=user_role.user_id").Joins("left join role on user_role.role_id=role.id").Order("user.id desc").Find(&users)
return users
}
func FindUserRole(query interface{},id interface{})User{
func FindUserRole(query interface{}, id interface{}) User {
var user User
DB.Select(query).Where("user.id = ?", id).Joins("join user_role on user.id=user_role.user_id").Joins("join role on user_role.role_id=role.id").First(&user)
return user
}
}

@ -2,88 +2,89 @@ package models
type Visitor struct {
Model
Name string `json:"name"`
Avator string `json:"avator"`
SourceIp string `json:"source_ip"`
ToId string `json:"to_id"`
Name string `json:"name"`
Avator string `json:"avator"`
SourceIp string `json:"source_ip"`
ToId string `json:"to_id"`
VisitorId string `json:"visitor_id"`
Status uint `json:"status"`
Refer string `json:"refer"`
City string `json:"city"`
ClientIp string `json:"client_ip"`
Status uint `json:"status"`
Refer string `json:"refer"`
City string `json:"city"`
ClientIp string `json:"client_ip"`
}
func CreateVisitor(name string,avator string,sourceIp string,toId string,visitorId string,refer string,city string,clientIp string){
old:=FindVisitorByVistorId(visitorId)
if old.Name!=""{
func CreateVisitor(name string, avator string, sourceIp string, toId string, visitorId string, refer string, city string, clientIp string) {
old := FindVisitorByVistorId(visitorId)
if old.Name != "" {
//更新状态上线
UpdateVisitor(visitorId,1,clientIp,sourceIp,refer)
UpdateVisitor(visitorId, 1, clientIp, sourceIp, refer)
return
}
v:=&Visitor{
Name:name,
Avator: avator,
SourceIp:sourceIp,
ToId:toId,
v := &Visitor{
Name: name,
Avator: avator,
SourceIp: sourceIp,
ToId: toId,
VisitorId: visitorId,
Status:1,
Refer:refer,
City:city,
ClientIp:clientIp,
Status: 1,
Refer: refer,
City: city,
ClientIp: clientIp,
}
DB.Create(v)
}
func FindVisitorByVistorId(visitorId string)Visitor{
func FindVisitorByVistorId(visitorId string) Visitor {
var v Visitor
DB.Where("visitor_id = ?", visitorId).First(&v)
return v
}
func FindVisitors(page uint,pagesize uint)[]Visitor{
offset:=(page-1)*pagesize
if offset<0{
offset=0
func FindVisitors(page uint, pagesize uint) []Visitor {
offset := (page - 1) * pagesize
if offset < 0 {
offset = 0
}
var visitors []Visitor
DB.Offset(offset).Limit(pagesize).Order("status desc, updated_at desc").Find(&visitors)
return visitors
}
func FindVisitorsByKefuId(page uint,pagesize uint,kefuId string)[]Visitor{
offset:=(page-1)*pagesize
if offset<0{
offset=0
func FindVisitorsByKefuId(page uint, pagesize uint, kefuId string) []Visitor {
offset := (page - 1) * pagesize
if offset < 0 {
offset = 0
}
var visitors []Visitor
DB.Where("to_id=?",kefuId).Offset(offset).Limit(pagesize).Order("status desc, updated_at desc").Find(&visitors)
DB.Where("to_id=?", kefuId).Offset(offset).Limit(pagesize).Order("status desc, updated_at desc").Find(&visitors)
return visitors
}
func FindVisitorsOnline()[]Visitor{
func FindVisitorsOnline() []Visitor {
var visitors []Visitor
DB.Where("status = ?",1).Find(&visitors)
DB.Where("status = ?", 1).Find(&visitors)
return visitors
}
func UpdateVisitorStatus(visitorId string,status uint){
visitor:=Visitor{
}
DB.Model(&visitor).Where("visitor_id = ?",visitorId).Update("status", status)
func UpdateVisitorStatus(visitorId string, status uint) {
visitor := Visitor{}
DB.Model(&visitor).Where("visitor_id = ?", visitorId).Update("status", status)
}
func UpdateVisitor(visitorId string,status uint,clientIp string,sourceIp string,refer string){
visitor:=&Visitor{
Status: status,
func UpdateVisitor(visitorId string, status uint, clientIp string, sourceIp string, refer string) {
visitor := &Visitor{
Status: status,
ClientIp: clientIp,
SourceIp: sourceIp,
Refer: refer,
Refer: refer,
}
DB.Model(visitor).Where("visitor_id = ?",visitorId).Update(visitor)
DB.Model(visitor).Where("visitor_id = ?", visitorId).Update(visitor)
}
//查询条数
func CountVisitors()uint{
func CountVisitors() uint {
var count uint
DB.Model(&Visitor{}).Count(&count)
return count
}
//查询条数
func CountVisitorsByKefuId(kefuId string)uint{
func CountVisitorsByKefuId(kefuId string) uint {
var count uint
DB.Model(&Visitor{}).Where("to_id=?",kefuId).Count(&count)
DB.Model(&Visitor{}).Where("to_id=?", kefuId).Count(&count)
return count
}
}

@ -3,34 +3,35 @@ package models
import "time"
type Welcome struct {
ID uint `gorm:"primary_key" json:"id"`
UserId string `json:"user_id"`
Content string `json:"content"`
IsDefault uint `json:"is_default"`
Ctime time.Time `json:"ctime"`
ID uint `gorm:"primary_key" json:"id"`
UserId string `json:"user_id"`
Content string `json:"content"`
IsDefault uint `json:"is_default"`
Ctime time.Time `json:"ctime"`
}
func CreateWelcome(userId string,content string)uint{
if userId==""||content==""{
func CreateWelcome(userId string, content string) uint {
if userId == "" || content == "" {
return 0
}
w:=&Welcome{
UserId: userId,
w := &Welcome{
UserId: userId,
Content: content,
Ctime: time.Now(),
Ctime: time.Now(),
}
DB.Create(w)
return w.ID
}
func FindWelcomeByUserId(userId interface{})Welcome{
func FindWelcomeByUserId(userId interface{}) Welcome {
var w Welcome
DB.Where("user_id = ? and is_default=?", userId,1).First(&w)
DB.Where("user_id = ? and is_default=?", userId, 1).First(&w)
return w
}
func FindWelcomesByUserId(userId interface{})[]Welcome{
func FindWelcomesByUserId(userId interface{}) []Welcome {
var w []Welcome
DB.Where("user_id = ?", userId).Find(&w)
return w
}
func DeleteWelcome(userId interface{},id string){
DB.Where("user_id = ? and id = ?", userId,id).Delete(Welcome{})
}
func DeleteWelcome(userId interface{}, id string) {
DB.Where("user_id = ? and id = ?", userId, id).Delete(Welcome{})
}

@ -6,56 +6,56 @@ import (
"github.com/taoshihan1991/imaptool/middleware"
)
func InitApiRouter(engine *gin.Engine){
func InitApiRouter(engine *gin.Engine) {
//首页
engine.GET("/", controller.Index)
engine.POST("/check", controller.LoginCheckPass)
engine.POST("/check_auth",middleware.JwtApiMiddleware, controller.MainCheckAuth)
engine.POST("/check_auth", middleware.JwtApiMiddleware, controller.MainCheckAuth)
//前后聊天
engine.GET("/chat_server",middleware.Ipblack, controller.NewChatServer)
engine.GET("/chat_server", middleware.Ipblack, controller.NewChatServer)
//获取消息
engine.GET("/messages", controller.GetVisitorMessage)
engine.GET("/message_notice", controller.SendVisitorNotice)
//发送单条消息
engine.POST("/message",middleware.Ipblack,controller.SendMessage)
engine.POST("/message", middleware.Ipblack, controller.SendMessage)
//上传文件
engine.POST("/uploadimg",middleware.Ipblack,controller.UploadImg)
engine.POST("/uploadimg", middleware.Ipblack, controller.UploadImg)
//获取未读消息数
engine.GET("/message_status",controller.GetVisitorMessage)
engine.GET("/message_status", controller.GetVisitorMessage)
//设置消息已读
engine.POST("/message_status",controller.GetVisitorMessage)
engine.POST("/message_status", controller.GetVisitorMessage)
//获取客服信息
engine.GET("/kefuinfo",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.GetKefuInfo)
engine.GET("/kefuinfo_setting",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.GetKefuInfoSetting)
engine.POST("/kefuinfo",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.PostKefuInfo)
engine.DELETE("/kefuinfo",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.DeleteKefuInfo)
engine.GET("/kefulist",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.GetKefuList)
engine.GET("/kefuinfo", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetKefuInfo)
engine.GET("/kefuinfo_setting", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetKefuInfoSetting)
engine.POST("/kefuinfo", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostKefuInfo)
engine.DELETE("/kefuinfo", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.DeleteKefuInfo)
engine.GET("/kefulist", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetKefuList)
//角色列表
engine.GET("/roles",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.GetRoleList)
engine.POST("/role",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.PostRole)
engine.GET("/roles", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetRoleList)
engine.POST("/role", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostRole)
//邮件夹列表
engine.GET("/folders", controller.GetFolders)
engine.GET("/mysql",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.MysqlGetConf)
engine.POST("/mysql",middleware.JwtApiMiddleware,middleware.RbacAuth, controller.MysqlSetConf)
engine.GET("/mysql", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.MysqlGetConf)
engine.POST("/mysql", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.MysqlSetConf)
engine.GET("/visitors_online", controller.GetVisitorOnlines)
engine.GET("/clear_online_tcp", controller.DeleteOnlineTcp)
engine.POST("/visitor_login",middleware.Ipblack,controller.PostVisitorLogin)
engine.POST("/visitor",controller.PostVisitor)
engine.GET("/visitor",middleware.JwtApiMiddleware, controller.GetVisitor)
engine.GET("/visitors",middleware.JwtApiMiddleware, controller.GetVisitors)
engine.GET("/statistics",middleware.JwtApiMiddleware, controller.GetStatistics)
engine.POST("/visitor_login", middleware.Ipblack, controller.PostVisitorLogin)
engine.POST("/visitor", controller.PostVisitor)
engine.GET("/visitor", middleware.JwtApiMiddleware, controller.GetVisitor)
engine.GET("/visitors", middleware.JwtApiMiddleware, controller.GetVisitors)
engine.GET("/statistics", middleware.JwtApiMiddleware, controller.GetStatistics)
//前台接口
engine.GET("/notice",middleware.SetLanguage, controller.GetNotice)
engine.POST("/notice",middleware.JwtApiMiddleware, controller.PostNotice)
engine.DELETE("/notice",middleware.JwtApiMiddleware, controller.DelNotice)
engine.GET("/notices",middleware.JwtApiMiddleware, controller.GetNotices)
engine.POST("/ipblack",middleware.JwtApiMiddleware,controller.PostIpblack)
engine.DELETE("/ipblack",middleware.JwtApiMiddleware,controller.DelIpblack)
engine.GET("/ipblacks_all",middleware.JwtApiMiddleware,controller.GetIpblacks)
engine.GET("/configs",middleware.JwtApiMiddleware,middleware.RbacAuth,controller.GetConfigs)
engine.POST("/config",middleware.JwtApiMiddleware,middleware.RbacAuth,controller.PostConfig)
engine.GET("/notice", middleware.SetLanguage, controller.GetNotice)
engine.POST("/notice", middleware.JwtApiMiddleware, controller.PostNotice)
engine.DELETE("/notice", middleware.JwtApiMiddleware, controller.DelNotice)
engine.GET("/notices", middleware.JwtApiMiddleware, controller.GetNotices)
engine.POST("/ipblack", middleware.JwtApiMiddleware, controller.PostIpblack)
engine.DELETE("/ipblack", middleware.JwtApiMiddleware, controller.DelIpblack)
engine.GET("/ipblacks_all", middleware.JwtApiMiddleware, controller.GetIpblacks)
engine.GET("/configs", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.GetConfigs)
engine.POST("/config", middleware.JwtApiMiddleware, middleware.RbacAuth, controller.PostConfig)
//微信接口
engine.GET("/micro_program",controller.GetCheckWeixinSign)
}
engine.GET("/micro_program", controller.GetCheckWeixinSign)
}

@ -6,21 +6,21 @@ import (
"github.com/taoshihan1991/imaptool/tmpl"
)
func InitViewRouter(engine *gin.Engine){
func InitViewRouter(engine *gin.Engine) {
engine.GET("/index", tmpl.PageIndex)
engine.GET("/login", tmpl.PageLogin)
engine.GET("/chat_page",middleware.SetLanguage, tmpl.PageChat)
engine.GET("/chatIndex",middleware.SetLanguage, tmpl.PageChat)
engine.GET("/chatKfIndex",tmpl.PageKfChat)
engine.GET("/main",middleware.JwtPageMiddleware,tmpl.PageMain)
engine.GET("/chat_main",middleware.JwtPageMiddleware,tmpl.PageChatMain)
engine.GET("/chat_page", middleware.SetLanguage, tmpl.PageChat)
engine.GET("/chatIndex", middleware.SetLanguage, tmpl.PageChat)
engine.GET("/chatKfIndex", tmpl.PageKfChat)
engine.GET("/main", middleware.JwtPageMiddleware, tmpl.PageMain)
engine.GET("/chat_main", middleware.JwtPageMiddleware, tmpl.PageChatMain)
engine.GET("/setting", tmpl.PageSetting)
engine.GET("/setting_mysql", tmpl.PageSettingMysql)
engine.GET("/setting_welcome", tmpl.PageSettingWelcome)
engine.GET("/setting_deploy", tmpl.PageSettingDeploy)
engine.GET("/setting_kefu_list",tmpl.PageKefuList)
engine.GET("/setting_ipblack",tmpl.PageIpblack)
engine.GET("/setting_config",tmpl.PageConfig)
engine.GET("/setting_kefu_list", tmpl.PageKefuList)
engine.GET("/setting_ipblack", tmpl.PageIpblack)
engine.GET("/setting_config", tmpl.PageConfig)
engine.GET("/mail_list", tmpl.PageMailList)
engine.GET("/roles_list", tmpl.PageRoleList)
engine.GET("/webjs", tmpl.PageWebJs)

@ -9,26 +9,26 @@ import (
//咨询界面
func PageChat(c *gin.Context) {
kefuId := c.Query("kefu_id")
lang,_ := c.Get("lang")
language:=config.CreateLanguage(lang.(string))
lang, _ := c.Get("lang")
language := config.CreateLanguage(lang.(string))
refer := c.Query("refer")
if refer==""{
refer=c.Request.Referer()
if refer == "" {
refer = c.Request.Referer()
}
c.HTML(http.StatusOK, "chat_page.html", gin.H{
"KEFU_ID":kefuId,
"SendBtn":language.Send,
"Lang":lang.(string),
"Refer":refer,
"KEFU_ID": kefuId,
"SendBtn": language.Send,
"Lang": lang.(string),
"Refer": refer,
})
}
func PageKfChat(c *gin.Context) {
kefuId := c.Query("kefu_id")
visitorId:=c.Query("visitor_id")
token:=c.Query("token")
visitorId := c.Query("visitor_id")
token := c.Query("token")
c.HTML(http.StatusOK, "chat_kf_page.html", gin.H{
"KefuId":kefuId,
"VisitorId":visitorId,
"Token":token,
"KefuId": kefuId,
"VisitorId": visitorId,
"Token": token,
})
}

@ -41,23 +41,24 @@ func (obj *CommonHtml) Display(file string, data interface{}) {
t, _ := template.New(file).Parse(main)
t.Execute(obj.Rw, data)
}
//首页
func PageIndex(c *gin.Context) {
lang := c.Query("lang")
if lang == "" ||lang!="cn"{
if lang == "" || lang != "cn" {
lang = "en"
}
language:=config.CreateLanguage(lang)
language := config.CreateLanguage(lang)
c.HTML(http.StatusOK, "index.html", gin.H{
"Copyright":language.WebCopyRight,
"WebDesc":language.MainIntro,
"SubIntro":language.IndexSubIntro,
"Document":language.IndexDocument,
"VisitorBtn":language.IndexVisitors,
"AgentBtn":language.IndexAgent,
"OnlineChat":language.IndexOnlineChat,
"IndexSend":language.Send,
"Lang":lang,
"Copyright": language.WebCopyRight,
"WebDesc": language.MainIntro,
"SubIntro": language.IndexSubIntro,
"Document": language.IndexDocument,
"VisitorBtn": language.IndexVisitors,
"AgentBtn": language.IndexAgent,
"OnlineChat": language.IndexOnlineChat,
"IndexSend": language.Send,
"Lang": lang,
})
}

@ -9,6 +9,3 @@ import (
func PageLogin(c *gin.Context) {
c.HTML(http.StatusOK, "login.html", nil)
}

@ -4,68 +4,75 @@ import (
"github.com/gin-gonic/gin"
"net/http"
)
//设置界面
func PageSetting(c *gin.Context) {
c.HTML(http.StatusOK, "setting.html", gin.H{
"tab_index":"1-1",
"action":"setting",
"tab_index": "1-1",
"action": "setting",
})
}
//设置欢迎
func PageSettingWelcome(c *gin.Context) {
c.HTML(http.StatusOK, "setting_welcome.html", gin.H{
"tab_index":"1-2",
"action":"setting_welcome",
"tab_index": "1-2",
"action": "setting_welcome",
})
}
//设置mysql
func PageSettingMysql(c *gin.Context) {
c.HTML(http.StatusOK, "setting_mysql.html", gin.H{
"tab_index":"2-4",
"action":"setting_mysql",
"tab_index": "2-4",
"action": "setting_mysql",
})
}
//设置部署
func PageSettingDeploy(c *gin.Context) {
c.HTML(http.StatusOK, "setting_deploy.html", gin.H{
"tab_index":"2-5",
"action":"setting_deploy",
"tab_index": "2-5",
"action": "setting_deploy",
})
}
//前台js部署
func PageWebJs(c *gin.Context){
c.HTML(http.StatusOK, "chat_web.js",nil)
func PageWebJs(c *gin.Context) {
c.HTML(http.StatusOK, "chat_web.js", nil)
}
//前台css部署
func PageWebCss(c *gin.Context){
c.HTML(http.StatusOK, "chat_web.css",nil)
func PageWebCss(c *gin.Context) {
c.HTML(http.StatusOK, "chat_web.css", nil)
}
func PageKefuList(c *gin.Context) {
c.HTML(http.StatusOK, "setting_kefu_list.html", gin.H{
"tab_index":"3-2",
"action":"setting_kefu_list",
"tab_index": "3-2",
"action": "setting_kefu_list",
})
}
//角色列表
func PageRoleList(c *gin.Context) {
c.HTML(http.StatusOK, "setting_role_list.html", gin.H{
"tab_index":"3-1",
"action":"roles_list",
"tab_index": "3-1",
"action": "roles_list",
})
}
//角色列表
func PageIpblack(c *gin.Context) {
c.HTML(http.StatusOK, "setting_ipblack.html", gin.H{
"tab_index":"4-5",
"action":"setting_ipblack",
"tab_index": "4-5",
"action": "setting_ipblack",
})
}
//配置项列表
func PageConfig(c *gin.Context) {
c.HTML(http.StatusOK, "setting_config.html", gin.H{
"tab_index":"4-6",
"action":"setting_config",
"tab_index": "4-6",
"action": "setting_config",
})
}

@ -5,8 +5,8 @@ import (
"net/http"
)
func Get(url string)string{
res, err :=http.Get(url)
func Get(url string) string {
res, err := http.Get(url)
if err != nil {
return ""
}

@ -4,13 +4,13 @@ import (
"github.com/ipipdotnet/ipdb-go"
)
func ParseIp(myip string)(*ipdb.CityInfo) {
func ParseIp(myip string) *ipdb.CityInfo {
db, err := ipdb.NewCity("./config/city.free.ipdb")
if err != nil {
return nil
}
db.Reload("./config/city.free.ipdb")
c,err :=db.FindInfo(myip, "CN")
c, err := db.FindInfo(myip, "CN")
if err != nil {
return nil
}

@ -16,4 +16,4 @@ func RedirectStderr(f *os.File) {
if err != nil {
log.Printf("Failed to redirect stderr to file: %v", err)
}
}
}

@ -38,4 +38,4 @@ func RedirectStderr(f *os.File) {
}
// SetStdHandle does not affect prior references to stderr
os.Stderr = f
}
}

@ -1,147 +1,153 @@
package tools
//划分
func partition(arr *[]int,left int,right int)int{
privot:=(*arr)[right]
i:=left-1
for j:=left;j<right;j++{
if (*arr)[j]<privot{
func partition(arr *[]int, left int, right int) int {
privot := (*arr)[right]
i := left - 1
for j := left; j < right; j++ {
if (*arr)[j] < privot {
i++
temp:=(*arr)[i]
(*arr)[i]=(*arr)[j]
(*arr)[j]=temp
temp := (*arr)[i]
(*arr)[i] = (*arr)[j]
(*arr)[j] = temp
}
}
temp:=(*arr)[i+1]
(*arr)[i+1]=(*arr)[right]
(*arr)[right]=temp
return i+1
temp := (*arr)[i+1]
(*arr)[i+1] = (*arr)[right]
(*arr)[right] = temp
return i + 1
}
//递归
func QuickSort(arr *[]int,left int,right int){
if left>= right{
func QuickSort(arr *[]int, left int, right int) {
if left >= right {
return
}
privot:=partition(arr,left,right)
QuickSort(arr,left,privot-1)
QuickSort(arr,privot+1,right)
privot := partition(arr, left, right)
QuickSort(arr, left, privot-1)
QuickSort(arr, privot+1, right)
}
//快速排序2
//找到一个基准,左边是所有比它小的,右边是比它大的,分别递归左右
func QuickSort2(arr *[]int,left int,right int){
if left>= right{
func QuickSort2(arr *[]int, left int, right int) {
if left >= right {
return
}
privot:=(*arr)[left]
i:=left
j:=right
for i<j{
for i<j && (*arr)[j]>privot{
privot := (*arr)[left]
i := left
j := right
for i < j {
for i < j && (*arr)[j] > privot {
j--
}
for i<j && (*arr)[i]<=privot{
for i < j && (*arr)[i] <= privot {
i++
}
temp:=(*arr)[i]
(*arr)[i]=(*arr)[j]
(*arr)[j]=temp
temp := (*arr)[i]
(*arr)[i] = (*arr)[j]
(*arr)[j] = temp
}
(*arr)[left]=(*arr)[i]
(*arr)[i]=privot
(*arr)[left] = (*arr)[i]
(*arr)[i] = privot
QuickSort(arr,left,i-1)
QuickSort(arr,i+1,right)
QuickSort(arr, left, i-1)
QuickSort(arr, i+1, right)
}
//冒泡排序
//比较相邻元素,较大的往右移
func BubbleSort(arr *[]int){
flag:=true
lastSwapIndex:=0
for i:=0;i<len(*arr)-1;i++{
sortBorder:=len(*arr)-1-i
for j:=0;j<sortBorder;j++{
if (*arr)[j]>(*arr)[j+1]{
temp:=(*arr)[j]
(*arr)[j]=(*arr)[j+1]
(*arr)[j+1]=temp
flag=false
lastSwapIndex=j
func BubbleSort(arr *[]int) {
flag := true
lastSwapIndex := 0
for i := 0; i < len(*arr)-1; i++ {
sortBorder := len(*arr) - 1 - i
for j := 0; j < sortBorder; j++ {
if (*arr)[j] > (*arr)[j+1] {
temp := (*arr)[j]
(*arr)[j] = (*arr)[j+1]
(*arr)[j+1] = temp
flag = false
lastSwapIndex = j
}
}
sortBorder=lastSwapIndex
if flag{
sortBorder = lastSwapIndex
if flag {
break
}
}
}
//插入排序
//将未排序部分插入到已排序部分的适当位置
func InsertionSort(arr *[]int){
for i:=1;i<len(*arr);i++{
curKey:=(*arr)[i]
j:=i-1
for curKey<(*arr)[j]{
(*arr)[j+1]=(*arr)[j]
func InsertionSort(arr *[]int) {
for i := 1; i < len(*arr); i++ {
curKey := (*arr)[i]
j := i - 1
for curKey < (*arr)[j] {
(*arr)[j+1] = (*arr)[j]
j--
if j<0 {
if j < 0 {
break
}
}
(*arr)[j+1]=curKey
(*arr)[j+1] = curKey
}
}
//选择排序
//选择一个最小值,再寻找比它还小的进行交换
func SelectionSort(arr *[]int){
for i:=0;i<len(*arr);i++{
minIndex:=i
for j:=i+1;j<len(*arr);j++{
if (*arr)[j]<(*arr)[minIndex]{
minIndex=j
func SelectionSort(arr *[]int) {
for i := 0; i < len(*arr); i++ {
minIndex := i
for j := i + 1; j < len(*arr); j++ {
if (*arr)[j] < (*arr)[minIndex] {
minIndex = j
}
}
temp:=(*arr)[i]
(*arr)[i]=(*arr)[minIndex]
(*arr)[minIndex]=temp
temp := (*arr)[i]
(*arr)[i] = (*arr)[minIndex]
(*arr)[minIndex] = temp
}
}
//归并排序
//合久必分,分久必合,利用临时数组合并两个有序数组
func MergeSort(arr *[]int,left int,right int){
if left >= right{
func MergeSort(arr *[]int, left int, right int) {
if left >= right {
return
}
mid:=(left+right)/2
MergeSort(arr,left,mid)
MergeSort(arr,mid+1,right)
mid := (left + right) / 2
MergeSort(arr, left, mid)
MergeSort(arr, mid+1, right)
i:=left
j:=mid+1
p:=0
temp :=make([]int,right-left+1)
for i<=mid && j<=right{
if (*arr)[i]<=(*arr)[j]{
temp[p]=(*arr)[i]
i := left
j := mid + 1
p := 0
temp := make([]int, right-left+1)
for i <= mid && j <= right {
if (*arr)[i] <= (*arr)[j] {
temp[p] = (*arr)[i]
i++
}else{
temp[p]=(*arr)[j]
} else {
temp[p] = (*arr)[j]
j++
}
p++
}
for i<=mid{
temp[p]=(*arr)[i]
for i <= mid {
temp[p] = (*arr)[i]
i++
p++
}
for j<=right{
temp[p]=(*arr)[j]
for j <= right {
temp[p] = (*arr)[j]
j++
p++
}
for i=0;i<len(temp);i++{
(*arr)[left+i]=temp[i]
for i = 0; i < len(temp); i++ {
(*arr)[left+i] = temp[i]
}
}

@ -5,38 +5,38 @@ import (
)
func TestQuickSort(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7}
arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr)
QuickSort(&arr,0,len(arr)-1)
QuickSort(&arr, 0, len(arr)-1)
t.Log(arr)
}
func TestQuickSort2(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7}
arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr)
QuickSort2(&arr,0,len(arr)-1)
QuickSort2(&arr, 0, len(arr)-1)
t.Log(arr)
}
func TestBubbleSort(t *testing.T){
arr:=[]int{6,8,3,9,4,5,4,7}
func TestBubbleSort(t *testing.T) {
arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr)
BubbleSort(&arr)
t.Log(arr)
}
func TestInsertionSort(t *testing.T){
arr:=[]int{6,8,3,9,4,5,4,7}
func TestInsertionSort(t *testing.T) {
arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr)
InsertionSort(&arr)
t.Log(arr)
}
func TestSelectionSort(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7}
arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr)
SelectionSort(&arr)
t.Log(arr)
}
func TestMergeSort(t *testing.T) {
arr:=[]int{6,8,3,9,4,5,4,7}
arr := []int{6, 8, 3, 9, 4, 5, 4, 7}
t.Log(arr)
MergeSort(&arr,0,len(arr)-1)
MergeSort(&arr, 0, len(arr)-1)
t.Log(arr)
}
}

@ -1,8 +1,10 @@
package tools
import (
"github.com/satori/go.uuid"
)
func Uuid()string {
func Uuid() string {
u2 := uuid.NewV4()
return u2.String()
}

Loading…
Cancel
Save