Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 253cad35ef | |||
| 47c8736f34 | |||
| dcce8ace9e | |||
| 125ccc5c3b | |||
| 432d59d483 | |||
| 60f222b011 | |||
| 7a8b86ed12 | |||
| b940afa6b0 | |||
| 8afd00ff86 | |||
| 8992fd6d3a | |||
| 524a892480 | |||
| c420e23edb | |||
| 7419e03d67 | |||
| 9425544d1c | |||
| a8d78832df | |||
| adfb2236dc | |||
| 6034598bb4 | |||
| 6fe44cb1cb | |||
| 39d67d1775 | |||
| a8f9f12bb8 | |||
| 2c1abb1d11 | |||
| 21e0219568 | |||
| 952c3a1243 | |||
| 33cd7ebd6b | |||
| be02b3418d | |||
| f390617167 | |||
| f7410200e3 | |||
| 9cfdfbac78 | |||
| b015e78fa0 | |||
| bb9092c3e5 | |||
| cc1bad8d3f | |||
| 8f7380d796 | |||
| f37b9aee70 | |||
| 1ab9027c93 | |||
| 96d341aaab | |||
| 1f25f511cc | |||
| 07c7a628d1 | |||
| d7a59845eb | |||
| 98619083a1 | |||
| c8a9038efe | |||
| b638d8bd65 | |||
| 77753a123f |
+2
-1
@@ -1,3 +1,4 @@
|
||||
/.idea/*
|
||||
.idea
|
||||
/example/config/app.json
|
||||
/example/config/app.json
|
||||
/example/tpt/demo/
|
||||
|
||||
+35
-57
@@ -7,8 +7,8 @@ import (
|
||||
. "code.hoteas.com/golang/hotime/db"
|
||||
. "code.hoteas.com/golang/hotime/log"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"github.com/sirupsen/logrus"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
@@ -23,7 +23,6 @@ type Application struct {
|
||||
MakeCodeRouter map[string]*code.MakeCode
|
||||
MethodRouter
|
||||
Router
|
||||
ContextBase
|
||||
Error
|
||||
Log *logrus.Logger
|
||||
WebConnectLog *logrus.Logger
|
||||
@@ -73,10 +72,18 @@ func (that *Application) Run(router Router) {
|
||||
if that.Router[k] == nil {
|
||||
that.Router[k] = v
|
||||
}
|
||||
|
||||
//直达接口层复用
|
||||
for k1, v1 := range v {
|
||||
that.Router[k][k1] = v1
|
||||
if that.Router[k][k1] == nil {
|
||||
that.Router[k][k1] = v1
|
||||
}
|
||||
|
||||
for k2, v2 := range v1 {
|
||||
|
||||
that.Router[k][k1][k2] = v2
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
//重新设置MethodRouter//直达路由
|
||||
that.MethodRouter = MethodRouter{}
|
||||
@@ -230,10 +237,8 @@ func (that *Application) SetConfig(configPath ...string) {
|
||||
|
||||
}
|
||||
|
||||
that.Log = GetLog(that.Config.GetString("logFile"), true)
|
||||
that.Error = Error{Logger: that.Log}
|
||||
if that.Config.Get("webConnectLogShow") == nil || that.Config.GetBool("webConnectLogShow") {
|
||||
that.WebConnectLog = GetLog(that.Config.GetString("webConnectLogFile"), false)
|
||||
if that.Error.GetError() != nil {
|
||||
fmt.Println(that.Error.GetError().Error())
|
||||
}
|
||||
|
||||
//文件如果损坏则不写入配置防止配置文件数据丢失
|
||||
@@ -260,6 +265,12 @@ func (that *Application) SetConfig(configPath ...string) {
|
||||
|
||||
}
|
||||
|
||||
that.Log = GetLog(that.Config.GetString("logFile"), true)
|
||||
that.Error = Error{Logger: that.Log}
|
||||
if that.Config.Get("webConnectLogShow") == nil || that.Config.GetBool("webConnectLogShow") {
|
||||
that.WebConnectLog = GetLog(that.Config.GetString("webConnectLogFile"), false)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// SetConnectListener 连接判断,返回false继续传输至控制层,true则停止传输
|
||||
@@ -555,13 +566,9 @@ func Init(config string) *Application {
|
||||
codeMake["name"] = codeMake.GetString("table")
|
||||
}
|
||||
|
||||
if appIns.Config.GetInt("mode") > 0 {
|
||||
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{}
|
||||
appIns.MakeCodeRouter[codeMake.GetString("name")].Db2JSON(&appIns.Db, codeMake)
|
||||
} else {
|
||||
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{}
|
||||
appIns.MakeCodeRouter[codeMake.GetString("name")].Db2JSON(nil, codeMake)
|
||||
}
|
||||
appIns.MakeCodeRouter[codeMake.GetString("name")] = &code.MakeCode{Error: appIns.Error}
|
||||
appIns.MakeCodeRouter[codeMake.GetString("name")].Db2JSON(&appIns.Db, codeMake)
|
||||
|
||||
//接入动态代码层
|
||||
if appIns.Router == nil {
|
||||
appIns.Router = Router{}
|
||||
@@ -608,6 +615,8 @@ func SetMysqlDB(appIns *Application, config Map) {
|
||||
appIns.Db.Type = "mysql"
|
||||
appIns.Db.DBName = config.GetString("name")
|
||||
appIns.Db.Prefix = config.GetString("prefix")
|
||||
appIns.Db.Log = appIns.Log
|
||||
appIns.Db.Mode = appIns.Config.GetCeilInt("mode")
|
||||
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
|
||||
//master数据库配置
|
||||
query := config.GetString("user") + ":" + config.GetString("password") +
|
||||
@@ -637,6 +646,8 @@ func SetSqliteDB(appIns *Application, config Map) {
|
||||
|
||||
appIns.Db.Type = "sqlite"
|
||||
appIns.Db.Prefix = config.GetString("prefix")
|
||||
appIns.Db.Mode = appIns.Config.GetCeilInt("mode")
|
||||
appIns.Db.Log = appIns.Log
|
||||
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
|
||||
db, e := sql.Open("sqlite3", config.GetString("path"))
|
||||
if e != nil && len(err) != 0 {
|
||||
@@ -652,48 +663,6 @@ func setMakeCodeLintener(name string, appIns *Application) {
|
||||
appIns.SetConnectListener(func(context *Context) (isFinished bool) {
|
||||
|
||||
codeIns := appIns.MakeCodeRouter[name]
|
||||
//文件上传接口
|
||||
if len(context.RouterString) == 1 && context.RouterString[0] == "file" && context.Req.Method == "POST" {
|
||||
if context.Session(codeIns.FileConfig.GetString("table")+"_id").Data == nil {
|
||||
context.Display(2, "你还没有登录")
|
||||
return true
|
||||
}
|
||||
//读取网络文件
|
||||
fi, fheader, err := context.Req.FormFile("file")
|
||||
if err != nil {
|
||||
context.Display(3, err)
|
||||
return true
|
||||
|
||||
}
|
||||
filePath := context.Config.GetString("filePath")
|
||||
if filePath == "" {
|
||||
filePath = "/file/2006/01/02/"
|
||||
}
|
||||
|
||||
path := time.Now().Format(filePath)
|
||||
e := os.MkdirAll(context.Config.GetString("tpt")+path, os.ModeDir)
|
||||
if e != nil {
|
||||
context.Display(3, e)
|
||||
return true
|
||||
}
|
||||
filePath = path + Md5(ObjToStr(RandX(100000, 9999999))) + fheader.Filename[strings.LastIndex(fheader.Filename, "."):]
|
||||
newFile, e := os.Create(context.Config.GetString("tpt") + filePath)
|
||||
|
||||
if e != nil {
|
||||
context.Display(3, e)
|
||||
return true
|
||||
}
|
||||
|
||||
_, e = io.Copy(newFile, fi)
|
||||
|
||||
if e != nil {
|
||||
context.Display(3, e)
|
||||
return true
|
||||
}
|
||||
|
||||
context.Display(0, filePath)
|
||||
return true
|
||||
}
|
||||
|
||||
if len(context.RouterString) < 2 || appIns.MakeCodeRouter[context.RouterString[0]] == nil {
|
||||
return isFinished
|
||||
@@ -707,6 +676,10 @@ func setMakeCodeLintener(name string, appIns *Application) {
|
||||
return isFinished
|
||||
}
|
||||
|
||||
if context.RouterString[1] == "hotime" && context.RouterString[2] == "config" {
|
||||
return isFinished
|
||||
}
|
||||
|
||||
if context.Session(codeIns.FileConfig.GetString("table")+"_id").Data == nil {
|
||||
context.Display(2, "你还没有登录")
|
||||
return true
|
||||
@@ -724,6 +697,11 @@ func setMakeCodeLintener(name string, appIns *Application) {
|
||||
context.Req.Method != "POST" {
|
||||
return isFinished
|
||||
}
|
||||
//排除已有接口的无效操作
|
||||
if len(context.RouterString) == 3 && context.Router[context.RouterString[0]] != nil && context.Router[context.RouterString[0]][context.RouterString[1]] != nil && context.Router[context.RouterString[0]][context.RouterString[1]][context.RouterString[2]] != nil {
|
||||
return isFinished
|
||||
}
|
||||
|
||||
//列表检索
|
||||
if len(context.RouterString) == 2 &&
|
||||
context.Req.Method == "GET" {
|
||||
|
||||
@@ -2,7 +2,13 @@ package hotime
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"fmt"
|
||||
"github.com/360EntSecGroup-Skylar/excelize"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Project 管理端项目
|
||||
@@ -12,8 +18,10 @@ var TptProject = Proj{
|
||||
"info": func(that *Context) {
|
||||
hotimeName := that.RouterString[0]
|
||||
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
|
||||
tableName := that.RouterString[1]
|
||||
|
||||
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
|
||||
str, inData := that.MakeCodeRouter[hotimeName].Info(that.RouterString[1], data, that.Db)
|
||||
str, inData := that.MakeCodeRouter[hotimeName].Info(tableName, data, that.Db)
|
||||
where := Map{"id": that.RouterString[2]}
|
||||
|
||||
if len(inData) == 1 {
|
||||
@@ -24,7 +32,7 @@ var TptProject = Proj{
|
||||
where = Map{"AND": where}
|
||||
}
|
||||
|
||||
re := that.Db.Get(that.RouterString[1], str, where)
|
||||
re := that.Db.Get(tableName, str, where)
|
||||
|
||||
if re == nil {
|
||||
that.Display(4, "找不到对应信息")
|
||||
@@ -32,7 +40,7 @@ var TptProject = Proj{
|
||||
}
|
||||
|
||||
for k, v := range re {
|
||||
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][k]
|
||||
column := that.MakeCodeRouter[hotimeName].TableColumns[tableName][k]
|
||||
if column == nil {
|
||||
continue
|
||||
}
|
||||
@@ -45,7 +53,7 @@ var TptProject = Proj{
|
||||
|
||||
link := strings.Replace(column.GetString("name"), "_id", "", -1)
|
||||
if link == "parent" {
|
||||
link = that.RouterString[1]
|
||||
link = tableName
|
||||
}
|
||||
re[link] = that.Db.Get(column.GetString("link"), seStr, Map{"id": v})
|
||||
}
|
||||
@@ -54,7 +62,7 @@ var TptProject = Proj{
|
||||
//如果有table字段则代为link
|
||||
if re["table"] != nil && re["table_id"] != nil {
|
||||
|
||||
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][re.GetString("table")]
|
||||
column := that.MakeCodeRouter[hotimeName].TableColumns[tableName][re.GetString("table")]
|
||||
v := re.GetCeilInt64("table_id")
|
||||
|
||||
seStr := "id," + column.GetString("value")
|
||||
@@ -65,7 +73,7 @@ var TptProject = Proj{
|
||||
|
||||
link := strings.Replace(column.GetString("name"), "_id", "", -1)
|
||||
if link == "parent" {
|
||||
link = that.RouterString[1]
|
||||
link = tableName
|
||||
}
|
||||
re[link] = that.Db.Get(column.GetString("link"), seStr, Map{"id": v})
|
||||
|
||||
@@ -74,67 +82,277 @@ var TptProject = Proj{
|
||||
that.Display(0, re)
|
||||
},
|
||||
"add": func(that *Context) {
|
||||
that.Log = Map{"table": that.RouterString[1], "type": 1}
|
||||
tableName := that.RouterString[1]
|
||||
that.Log = Map{"table": tableName, "type": 1}
|
||||
|
||||
hotimeName := that.RouterString[0]
|
||||
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
|
||||
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
|
||||
inData := that.MakeCodeRouter[hotimeName].Add(that.RouterString[1], data, that.Req)
|
||||
inData := that.MakeCodeRouter[hotimeName].Add(tableName, data, that.Req)
|
||||
if inData == nil {
|
||||
that.Display(3, "请求参数不足")
|
||||
return
|
||||
}
|
||||
|
||||
re := that.Db.Insert(that.RouterString[1], inData)
|
||||
for _, v := range that.MakeCodeRouter[hotimeName].TableColumns[fileConfig.GetString("table")] {
|
||||
if v.GetString("link") != "" {
|
||||
|
||||
if v.GetString("link") == tableName && that.MakeCodeRouter[hotimeName].TableColumns[v.GetString("link")]["parent_id"] != nil {
|
||||
if inData["parent_id"] == nil && data[v.GetString("name")] != nil {
|
||||
inData["parent_id"] = data.GetCeilInt64(v.GetString("name"))
|
||||
pre := that.Db.Get(v.GetString("link"), "parent_ids", Map{"id": data.GetCeilInt64(v.GetString("name"))})
|
||||
inData["parent_ids"] = pre.GetString("parent_ids")
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if v.GetString("link") == tableName && that.MakeCodeRouter[hotimeName].TableColumns[v.GetString("link")]["auth"] != nil {
|
||||
linkAuthMap := that.Db.Get(v.GetString("link"), "auth", Map{"id": data.GetCeilInt(v.GetString("name"))})
|
||||
linkAuth := linkAuthMap.GetMap("auth")
|
||||
|
||||
if linkAuth == nil {
|
||||
btes, err := ioutil.ReadFile(fileConfig.GetString("config"))
|
||||
if err != nil {
|
||||
that.Display(4, "找不到配置文件")
|
||||
return
|
||||
}
|
||||
linkAuth = Map{}
|
||||
conf := ObjToMap(string(btes))
|
||||
menus := conf.GetSlice("menus")
|
||||
|
||||
for k1, _ := range menus {
|
||||
v1 := menus.GetMap(k1)
|
||||
name := v1.GetString("name")
|
||||
if name == "" {
|
||||
name = v1.GetString("table")
|
||||
}
|
||||
if v1["auth"] != nil {
|
||||
linkAuth[name] = v1["auth"]
|
||||
|
||||
}
|
||||
if v1["auth"] == nil {
|
||||
table := that.MakeCodeRouter[hotimeName].TableConfig.GetMap(name)
|
||||
if table != nil {
|
||||
linkAuth[name] = that.MakeCodeRouter[hotimeName].TableConfig.GetMap(name)["auth"]
|
||||
} else {
|
||||
linkAuth[name] = Slice{"show"}
|
||||
}
|
||||
}
|
||||
|
||||
menusChild := v1.GetSlice("menus")
|
||||
for k2, _ := range menusChild {
|
||||
v2 := menusChild.GetMap(k2)
|
||||
name := v2.GetString("name")
|
||||
if name == "" {
|
||||
name = v2.GetString("table")
|
||||
}
|
||||
if v2["auth"] != nil {
|
||||
linkAuth[name] = v2["auth"]
|
||||
continue
|
||||
}
|
||||
if v2["auth"] == nil {
|
||||
table := that.MakeCodeRouter[hotimeName].TableConfig.GetMap(name)
|
||||
if table != nil {
|
||||
linkAuth[name] = that.MakeCodeRouter[hotimeName].TableConfig.GetMap(name)["auth"]
|
||||
} else {
|
||||
linkAuth[name] = Slice{"show"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toDB := Map{}
|
||||
newAuth := inData.GetMap("auth")
|
||||
if newAuth == nil {
|
||||
inData["auth"] = linkAuth.ToJsonString()
|
||||
continue
|
||||
}
|
||||
|
||||
for k1, _ := range newAuth {
|
||||
v1 := newAuth.GetSlice(k1)
|
||||
if linkAuth.GetString(k1) == "" {
|
||||
continue
|
||||
}
|
||||
toDbli := Slice{}
|
||||
for k2, _ := range v1 {
|
||||
v2 := v1.GetString(k2)
|
||||
|
||||
if !strings.Contains(linkAuth.GetString(k1), `"`+v2+`"`) {
|
||||
continue
|
||||
}
|
||||
toDbli = append(toDbli, v2)
|
||||
}
|
||||
toDB[k1] = toDbli
|
||||
}
|
||||
|
||||
inData["auth"] = toDB.ToJsonString()
|
||||
//break
|
||||
}
|
||||
}
|
||||
|
||||
re := that.Db.Insert(tableName, inData)
|
||||
|
||||
if re == 0 {
|
||||
that.Display(4, "无法插入对应数据")
|
||||
return
|
||||
}
|
||||
//索引管理,便于检索以及权限
|
||||
if inData.Get("parent_id") != nil && inData.GetString("index") != "" {
|
||||
index := that.Db.Get(that.RouterString[1], "`index`", Map{"id": inData.Get("parent_id")})
|
||||
inData["index"] = index.GetString("index") + ObjToStr(re) + ","
|
||||
that.Db.Update(that.RouterString[1], Map{"index": inData["index"]}, Map{"id": re})
|
||||
} else if inData.GetString("index") != "" {
|
||||
inData["index"] = "," + ObjToStr(re) + ","
|
||||
that.Db.Update(that.RouterString[1], Map{"index": inData["index"]}, Map{"id": re})
|
||||
if inData.Get("parent_id") != nil && inData.GetString("parent_ids") != "" {
|
||||
index := that.Db.Get(tableName, "`parent_ids`", Map{"id": inData.Get("parent_id")})
|
||||
inData["parent_ids"] = index.GetString("parent_ids") + ObjToStr(re) + ","
|
||||
that.Db.Update(tableName, Map{"parent_ids": inData["parent_ids"]}, Map{"id": re})
|
||||
} else if inData.GetString("parent_ids") != "" {
|
||||
inData["parent_ids"] = "," + ObjToStr(re) + ","
|
||||
that.Db.Update(tableName, Map{"parent_ids": inData["parent_ids"]}, Map{"id": re})
|
||||
}
|
||||
that.Log["table_id"] = re
|
||||
that.Display(0, re)
|
||||
},
|
||||
"update": func(that *Context) {
|
||||
|
||||
that.Log = Map{"table": that.RouterString[1], "type": 2, "table_id": that.RouterString[2]}
|
||||
tableName := that.RouterString[1]
|
||||
that.Log = Map{"table": tableName, "type": 2, "table_id": that.RouterString[2]}
|
||||
|
||||
hotimeName := that.RouterString[0]
|
||||
inData := that.MakeCodeRouter[hotimeName].Edit(that.RouterString[1], that.Req)
|
||||
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
|
||||
|
||||
inData := that.MakeCodeRouter[hotimeName].Edit(tableName, that.Req)
|
||||
|
||||
if inData == nil {
|
||||
that.Display(3, "没有找到要更新的数据")
|
||||
return
|
||||
}
|
||||
|
||||
//索引管理,便于检索以及权限
|
||||
if inData.GetString("index") != "" {
|
||||
if inData.Get("parent_id") != nil {
|
||||
Index := that.Db.Get(that.RouterString[1], "`index`", Map{"id": that.RouterString[2]})
|
||||
parentIndex := that.Db.Get(that.RouterString[1], "`index`", Map{"id": inData.Get("parent_id")})
|
||||
inData["index"] = parentIndex.GetString("index") + that.RouterString[2] + ","
|
||||
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
|
||||
|
||||
childNodes := that.Db.Select(that.RouterString[1], "id,`index``", Map{"index[~]": "," + that.RouterString[2] + ","})
|
||||
//树状结构不允许修改自身的属性,修改别人的可以
|
||||
btes, err := ioutil.ReadFile(fileConfig.GetString("config"))
|
||||
if err != nil {
|
||||
that.Display(4, "找不到权限配置文件")
|
||||
return
|
||||
}
|
||||
|
||||
for _, v := range childNodes {
|
||||
v["index"] = strings.Replace(v.GetString("index"), Index.GetString("index"), inData.GetString("index"), -1)
|
||||
that.Db.Update(that.RouterString[1], Map{"index": v["index"]}, Map{"id": v.GetCeilInt("id")})
|
||||
}
|
||||
} else {
|
||||
delete(inData, "index")
|
||||
conf := ObjToMap(string(btes))
|
||||
|
||||
stop := conf.GetSlice("stop")
|
||||
for k, _ := range stop {
|
||||
v := stop.GetString(k)
|
||||
//不能改对应行数据
|
||||
if tableName == v && data.GetCeilInt64(v+"_id") == ObjToCeilInt64(that.RouterString[2]) {
|
||||
that.Display(4, "你没有权限修改当前数据")
|
||||
return
|
||||
}
|
||||
//不能改自身对应的数据
|
||||
if tableName == fileConfig.GetString("table") && inData[v+"_id"] != nil {
|
||||
delete(inData, v+"_id")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
re := that.Db.Update(that.RouterString[1], inData, Map{"id": that.RouterString[2]})
|
||||
if inData["auth"] != nil {
|
||||
menus := conf.GetSlice("menus")
|
||||
for _, v := range that.MakeCodeRouter[hotimeName].TableColumns[fileConfig.GetString("table")] {
|
||||
|
||||
if v.GetString("link") != "" && that.MakeCodeRouter[hotimeName].TableColumns[v.GetString("link")]["auth"] != nil {
|
||||
linkAuthMap := that.Db.Get(v.GetString("link"), "auth", Map{"id": data.GetCeilInt(v.GetString("name"))})
|
||||
linkAuth := linkAuthMap.GetMap("auth")
|
||||
|
||||
if linkAuth == nil {
|
||||
|
||||
linkAuth = Map{}
|
||||
for k1, _ := range menus {
|
||||
v1 := menus.GetMap(k1)
|
||||
name := v1.GetString("name")
|
||||
if name == "" {
|
||||
name = v1.GetString("table")
|
||||
}
|
||||
if v1["auth"] != nil {
|
||||
linkAuth[name] = v1["auth"]
|
||||
continue
|
||||
}
|
||||
if v1["auth"] == nil {
|
||||
|
||||
table := that.MakeCodeRouter[hotimeName].TableConfig.GetMap(name)
|
||||
if table != nil {
|
||||
linkAuth[name] = that.MakeCodeRouter[hotimeName].TableConfig.GetMap(name)["auth"]
|
||||
} else {
|
||||
linkAuth[name] = Slice{"show"}
|
||||
}
|
||||
}
|
||||
menusChild := v1.GetSlice("menus")
|
||||
for k2, _ := range menusChild {
|
||||
v2 := menusChild.GetMap(k2)
|
||||
name := v2.GetString("name")
|
||||
if name == "" {
|
||||
name = v2.GetString("table")
|
||||
}
|
||||
if v2["auth"] != nil {
|
||||
linkAuth[name] = v2["auth"]
|
||||
continue
|
||||
}
|
||||
if v2["auth"] == nil {
|
||||
table := that.MakeCodeRouter[hotimeName].TableConfig.GetMap(name)
|
||||
if table != nil {
|
||||
linkAuth[name] = that.MakeCodeRouter[hotimeName].TableConfig.GetMap(name)["auth"]
|
||||
} else {
|
||||
linkAuth[name] = Slice{"show"}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
toDB := Map{}
|
||||
newAuth := inData.GetMap("auth")
|
||||
if newAuth == nil || len(newAuth) == 0 {
|
||||
inData["auth"] = linkAuth.ToJsonString()
|
||||
break
|
||||
}
|
||||
//不可超出用户权限
|
||||
for k1, _ := range newAuth {
|
||||
v1 := newAuth.GetSlice(k1)
|
||||
if linkAuth.GetString(k1) == "" {
|
||||
continue
|
||||
}
|
||||
toDbli := Slice{}
|
||||
for k2, _ := range v1 {
|
||||
v2 := v1.GetString(k2)
|
||||
if !strings.Contains(linkAuth.GetString(k1), `"`+v2+`"`) {
|
||||
continue
|
||||
}
|
||||
toDbli = append(toDbli, v2)
|
||||
}
|
||||
toDB[k1] = toDbli
|
||||
}
|
||||
|
||||
inData["auth"] = toDB.ToJsonString()
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//索引管理,便于检索以及权限
|
||||
if inData.GetString("parent_ids") != "" {
|
||||
if inData.Get("parent_id") != nil {
|
||||
Index := that.Db.Get(tableName, "`index`", Map{"id": that.RouterString[2]})
|
||||
parentIndex := that.Db.Get(tableName, "`index`", Map{"id": inData.Get("parent_id")})
|
||||
inData["parent_ids"] = parentIndex.GetString("parent_ids") + that.RouterString[2] + ","
|
||||
|
||||
childNodes := that.Db.Select(tableName, "id,`index``", Map{"index[~]": "," + that.RouterString[2] + ","})
|
||||
|
||||
for _, v := range childNodes {
|
||||
v["parent_ids"] = strings.Replace(v.GetString("parent_ids"), Index.GetString("parent_ids"), inData.GetString("parent_ids"), -1)
|
||||
that.Db.Update(tableName, Map{"parent_ids": v["parent_ids"]}, Map{"id": v.GetCeilInt("id")})
|
||||
}
|
||||
} else {
|
||||
delete(inData, "parent_ids")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
re := that.Db.Update(tableName, inData, Map{"id": that.RouterString[2]})
|
||||
|
||||
if re == 0 {
|
||||
that.Display(4, "更新数据失败")
|
||||
@@ -144,19 +362,20 @@ var TptProject = Proj{
|
||||
that.Display(0, re)
|
||||
},
|
||||
"remove": func(that *Context) {
|
||||
that.Log = Map{"table": that.RouterString[1], "type": 3, "table_id": that.RouterString[2]}
|
||||
tableName := that.RouterString[1]
|
||||
that.Log = Map{"table": tableName, "type": 3, "table_id": that.RouterString[2]}
|
||||
hotimeName := that.RouterString[0]
|
||||
inData := that.MakeCodeRouter[hotimeName].Delete(that.RouterString[1], that.Req)
|
||||
inData := that.MakeCodeRouter[hotimeName].Delete(tableName, that.Req)
|
||||
if inData == nil {
|
||||
that.Display(3, "请求参数不足")
|
||||
return
|
||||
}
|
||||
re := int64(0)
|
||||
//索引管理,便于检索以及权限
|
||||
if inData.Get("parent_id") != nil && inData.GetSlice("index") != nil {
|
||||
re = that.Db.Delete(that.RouterString[1], Map{"index[~]": "," + that.RouterString[2] + ","})
|
||||
if inData.Get("parent_id") != nil && inData.GetSlice("parent_ids") != nil {
|
||||
re = that.Db.Delete(tableName, Map{"index[~]": "," + that.RouterString[2] + ","})
|
||||
} else {
|
||||
re = that.Db.Delete(that.RouterString[1], Map{"id": that.RouterString[2]})
|
||||
re = that.Db.Delete(tableName, Map{"id": that.RouterString[2]})
|
||||
}
|
||||
|
||||
if re == 0 {
|
||||
@@ -165,18 +384,19 @@ var TptProject = Proj{
|
||||
}
|
||||
that.Display(0, "删除成功")
|
||||
},
|
||||
|
||||
"search": func(that *Context) {
|
||||
hotimeName := that.RouterString[0]
|
||||
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
|
||||
|
||||
tableName := that.RouterString[1]
|
||||
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
|
||||
|
||||
columnStr, leftJoin, where := that.MakeCodeRouter[hotimeName].Search(that.RouterString[1], data, that.Req, that.Db)
|
||||
columnStr, leftJoin, where := that.MakeCodeRouter[hotimeName].Search(tableName, data, that.Req, that.Db)
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
download := ObjToInt(that.Req.FormValue("download"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
@@ -185,31 +405,49 @@ var TptProject = Proj{
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
count := that.Db.Count(that.RouterString[1], leftJoin, where)
|
||||
reData := that.Db.Page(page, pageSize).
|
||||
PageSelect(that.RouterString[1], leftJoin, columnStr, where)
|
||||
var count int
|
||||
var reData []Map
|
||||
//是否下载
|
||||
if download == 0 {
|
||||
count = that.Db.Count(tableName, leftJoin, where)
|
||||
reData = that.Db.Page(page, pageSize).
|
||||
PageSelect(tableName, leftJoin, columnStr, where)
|
||||
}
|
||||
if download == 1 {
|
||||
reData = that.Db.Select(tableName, leftJoin, columnStr, where)
|
||||
}
|
||||
|
||||
for _, v := range reData {
|
||||
v.RangeSort(func(k string, v1 interface{}) (isEnd bool) {
|
||||
|
||||
for k, _ := range v {
|
||||
//v1:=v.GetMap(k)
|
||||
//v.RangeSort(func(k string, v1 interface{}) (isEnd bool) {
|
||||
//如果有table字段则代为link
|
||||
if v["table"] != nil && v["table_id"] != nil {
|
||||
|
||||
id := v.GetCeilInt64("table_id")
|
||||
tableName := that.MakeCodeRouter[hotimeName].TableConfig.GetMap(v.GetString("table")).GetString("label")
|
||||
v["table_table_name"] = strings.Replace(tableName, "管理", "", -1)
|
||||
parentC := that.Db.Get(v.GetString("table"), "name", Map{"id": id})
|
||||
tableNameLabel := that.MakeCodeRouter[hotimeName].TableConfig.GetMap(v.GetString("table")).GetString("label")
|
||||
//v["table_table_name"] = strings.Replace(tableNameLabel, "管理", "", -1)
|
||||
v["table_table_name"] = tableNameLabel
|
||||
sname := "name"
|
||||
if that.MakeCodeRouter[hotimeName].TableColumns[v.GetString("table")][sname] == nil {
|
||||
sname = "title"
|
||||
if that.MakeCodeRouter[hotimeName].TableColumns[v.GetString("table")][sname] == nil {
|
||||
sname = "id"
|
||||
}
|
||||
}
|
||||
|
||||
parentC := that.Db.Get(v.GetString("table"), sname, Map{"id": id})
|
||||
v["table_table_id_name"] = ""
|
||||
if parentC != nil {
|
||||
v["table_table_id_name"] = parentC.GetString("name")
|
||||
v["table_table_id_name"] = parentC.GetString(sname)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
column := that.MakeCodeRouter[hotimeName].TableColumns[that.RouterString[1]][k]
|
||||
column := that.MakeCodeRouter[hotimeName].TableColumns[tableName][k]
|
||||
|
||||
if column == nil {
|
||||
return isEnd
|
||||
break
|
||||
}
|
||||
|
||||
if (column["list"] == nil || column["list"] == true) && column["name"] == "parent_id" && column.GetString("link") != "" {
|
||||
@@ -221,14 +459,208 @@ var TptProject = Proj{
|
||||
}
|
||||
}
|
||||
|
||||
return isEnd
|
||||
})
|
||||
//return isEnd
|
||||
}
|
||||
}
|
||||
|
||||
if download == 1 {
|
||||
|
||||
tableNameLabel := that.MakeCodeRouter[hotimeName].TableConfig.GetMap(tableName).GetString("label")
|
||||
f := excelize.NewFile()
|
||||
// 创建一个工作表
|
||||
f.NewSheet(tableNameLabel)
|
||||
|
||||
f.DeleteSheet("Sheet1")
|
||||
columns := that.MakeCodeRouter[hotimeName].TableConfig.GetMap(tableName).GetSlice("columns")
|
||||
//单列
|
||||
n := 0
|
||||
for k, _ := range columns {
|
||||
v := columns.GetMap(k)
|
||||
if v["list"] != nil && v.GetBool("list") == false {
|
||||
continue
|
||||
}
|
||||
n++
|
||||
//第一个要加状态行
|
||||
//单行
|
||||
for k1, v1 := range reData {
|
||||
if k1 == 0 {
|
||||
f.SetCellValue(tableNameLabel, convertToTitle(n)+"1", v.GetString("label"))
|
||||
}
|
||||
|
||||
if v.GetString("link") != "" {
|
||||
f.SetCellValue(tableNameLabel, convertToTitle(n)+ObjToStr(k1+2), v1.GetString(v.GetString("link")+"_"+v.GetString("name")+"_"+v.GetString("value")))
|
||||
continue
|
||||
}
|
||||
|
||||
if v.GetString("name") == "table" {
|
||||
f.SetCellValue(tableNameLabel, convertToTitle(n)+ObjToStr(k1+2), v1.GetString("table_"+v.GetString("name")+"_name"))
|
||||
continue
|
||||
}
|
||||
|
||||
if v.GetString("name") == "table_id" {
|
||||
f.SetCellValue(tableNameLabel, convertToTitle(n)+ObjToStr(k1+2), v1.GetString("table_"+v.GetString("name")+"_name"))
|
||||
continue
|
||||
}
|
||||
|
||||
//select类型
|
||||
options := v.GetSlice("options")
|
||||
if len(options) != 0 {
|
||||
isEnd := false
|
||||
for ok, _ := range options {
|
||||
ov := options.GetMap(ok)
|
||||
if ov.GetString("value") == v1.GetString(v.GetString("name")) {
|
||||
f.SetCellValue(tableNameLabel, convertToTitle(n)+ObjToStr(k1+2), ov.GetString("name"))
|
||||
isEnd = true
|
||||
break
|
||||
}
|
||||
|
||||
}
|
||||
if isEnd {
|
||||
continue
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
f.SetCellValue(tableNameLabel, convertToTitle(n)+ObjToStr(k1+2), v1.GetString(v.GetString("name")))
|
||||
}
|
||||
}
|
||||
filePath := that.Config.GetString("filePath")
|
||||
if filePath == "" {
|
||||
filePath = "/file/temp/"
|
||||
}
|
||||
|
||||
//path := time.Now().Format(filePath)
|
||||
e := os.MkdirAll(that.Config.GetString("tpt")+filePath, os.ModeDir)
|
||||
if e != nil {
|
||||
that.Display(3, e)
|
||||
return
|
||||
}
|
||||
filePath = filePath + tableName + time.Now().Format("2006-01-02-15-04-05") + ".xlsx"
|
||||
|
||||
// 根据指定路径保存文件
|
||||
if err := f.SaveAs(that.Config.GetString("tpt") + filePath); err != nil {
|
||||
fmt.Println(err)
|
||||
that.Display(4, "输出异常")
|
||||
return
|
||||
}
|
||||
f.Save()
|
||||
//that.Resp.Header().Set("Location", filePath)
|
||||
//that.Resp.WriteHeader(307) //关键在这里!
|
||||
that.Display(0, filePath)
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, Map{"count": count, "data": reData})
|
||||
},
|
||||
},
|
||||
"hotime": Ctr{
|
||||
"file": func(that *Context) {
|
||||
//文件上传接口
|
||||
hotimeName := that.RouterString[0]
|
||||
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
|
||||
if that.Session(fileConfig.GetString("table")+"_id").Data == nil {
|
||||
that.Display(2, "你还没有登录")
|
||||
return
|
||||
}
|
||||
//读取网络文件
|
||||
fi, fheader, err := that.Req.FormFile("file")
|
||||
if err != nil {
|
||||
that.Display(3, err)
|
||||
return
|
||||
|
||||
}
|
||||
filePath := that.Config.GetString("filePath")
|
||||
if filePath == "" {
|
||||
filePath = "/file/2006/01/02/"
|
||||
}
|
||||
|
||||
path := time.Now().Format(filePath)
|
||||
e := os.MkdirAll(that.Config.GetString("tpt")+path, os.ModeDir)
|
||||
if e != nil {
|
||||
that.Display(3, e)
|
||||
return
|
||||
}
|
||||
filePath = path + Md5(ObjToStr(RandX(100000, 9999999))) + fheader.Filename[strings.LastIndex(fheader.Filename, "."):]
|
||||
newFile, e := os.Create(that.Config.GetString("tpt") + filePath)
|
||||
|
||||
if e != nil {
|
||||
that.Display(3, e)
|
||||
return
|
||||
}
|
||||
|
||||
_, e = io.Copy(newFile, fi)
|
||||
|
||||
if e != nil {
|
||||
that.Display(3, e)
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, filePath)
|
||||
},
|
||||
"info": func(that *Context) {
|
||||
hotimeName := that.RouterString[0]
|
||||
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
|
||||
tableName := fileConfig.GetString("table")
|
||||
|
||||
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
|
||||
str, inData := that.MakeCodeRouter[hotimeName].Info(tableName, data, that.Db)
|
||||
where := Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()}
|
||||
|
||||
if len(inData) == 1 {
|
||||
inData["id"] = where["id"]
|
||||
where = Map{"AND": inData}
|
||||
} else if len(inData) > 1 {
|
||||
where["OR"] = inData
|
||||
where = Map{"AND": where}
|
||||
}
|
||||
|
||||
re := that.Db.Get(tableName, str, where)
|
||||
if re == nil {
|
||||
that.Display(4, "找不到对应信息")
|
||||
return
|
||||
}
|
||||
|
||||
for k, v := range re {
|
||||
column := that.MakeCodeRouter[hotimeName].TableColumns[tableName][k]
|
||||
if column == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
if (column["list"] == nil || column.GetBool("list")) && column.GetString("link") != "" {
|
||||
seStr := "id," + column.GetString("value")
|
||||
if that.MakeCodeRouter[hotimeName].TableColumns[column.GetString("link")]["phone"] != nil {
|
||||
seStr = seStr + ",phone"
|
||||
}
|
||||
|
||||
link := strings.Replace(column.GetString("name"), "_id", "", -1)
|
||||
if link == "parent" {
|
||||
link = tableName
|
||||
}
|
||||
re[link] = that.Db.Get(column.GetString("link"), seStr, Map{"id": v})
|
||||
}
|
||||
}
|
||||
//如果有table字段则代为link
|
||||
if re["table"] != nil && re["table_id"] != nil {
|
||||
|
||||
column := that.MakeCodeRouter[hotimeName].TableColumns[tableName][re.GetString("table")]
|
||||
v := re.GetCeilInt64("table_id")
|
||||
|
||||
seStr := "id," + column.GetString("value")
|
||||
|
||||
if that.MakeCodeRouter[hotimeName].TableColumns[column.GetString("link")]["phone"] != nil {
|
||||
seStr = seStr + ",phone"
|
||||
}
|
||||
|
||||
link := strings.Replace(column.GetString("name"), "_id", "", -1)
|
||||
if link == "parent" {
|
||||
link = tableName
|
||||
}
|
||||
re[link] = that.Db.Get(column.GetString("link"), seStr, Map{"id": v})
|
||||
|
||||
}
|
||||
re["table"] = fileConfig.GetString("table")
|
||||
that.Display(0, re)
|
||||
},
|
||||
"login": func(that *Context) {
|
||||
hotimeName := that.RouterString[0]
|
||||
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
|
||||
@@ -239,7 +671,20 @@ var TptProject = Proj{
|
||||
that.Display(3, "参数不足")
|
||||
return
|
||||
}
|
||||
user := that.Db.Get(fileConfig.GetString("table"), "*", Map{"AND": Map{"OR": Map{"name": name, "phone": name}, "password": Md5(password)}})
|
||||
|
||||
where := Map{"name": name}
|
||||
if that.MakeCodeRouter[hotimeName].TableColumns[fileConfig.GetString("table")]["phone"] != nil {
|
||||
where["phone"] = name
|
||||
where = Map{"OR": where, "password": Md5(password)}
|
||||
} else {
|
||||
where["password"] = Md5(password)
|
||||
}
|
||||
|
||||
if len(where) > 1 {
|
||||
where = Map{"AND": where}
|
||||
}
|
||||
|
||||
user := that.Db.Get(fileConfig.GetString("table"), "*", where)
|
||||
|
||||
if user == nil {
|
||||
that.Display(5, "登录失败")
|
||||
@@ -248,8 +693,11 @@ var TptProject = Proj{
|
||||
that.Session(fileConfig.GetString("table")+"_id", user.GetCeilInt("id"))
|
||||
that.Session(fileConfig.GetString("table")+"_name", name)
|
||||
delete(user, "password")
|
||||
user["table"] = fileConfig.GetString("table")
|
||||
user["token"] = that.SessionId
|
||||
that.Display(0, user)
|
||||
},
|
||||
|
||||
"logout": func(that *Context) {
|
||||
hotimeName := that.RouterString[0]
|
||||
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
|
||||
@@ -257,45 +705,202 @@ var TptProject = Proj{
|
||||
that.Session(fileConfig.GetString("table")+"_name", nil)
|
||||
that.Display(0, "退出登录成功")
|
||||
},
|
||||
"info": func(that *Context) {
|
||||
"config": func(that *Context) {
|
||||
|
||||
hotimeName := that.RouterString[0]
|
||||
fileConfig := that.MakeCodeRouter[hotimeName].FileConfig
|
||||
btes, err := ioutil.ReadFile(fileConfig.GetString("config"))
|
||||
|
||||
data := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()})
|
||||
str, inData := that.MakeCodeRouter[hotimeName].Info(fileConfig.GetString("table"), data, that.Db)
|
||||
where := Map{"id": that.Session(fileConfig.GetString("table") + "_id").ToCeilInt()}
|
||||
if len(inData) == 1 {
|
||||
inData["id"] = where["id"]
|
||||
where = Map{"AND": inData}
|
||||
} else if len(inData) > 1 {
|
||||
where["OR"] = inData
|
||||
where = Map{"AND": where}
|
||||
}
|
||||
re := that.Db.Get(fileConfig.GetString("table"), str, where)
|
||||
if re == nil {
|
||||
that.Display(4, "找不到对应信息")
|
||||
if err != nil {
|
||||
that.Display(4, "找不到配置文件")
|
||||
return
|
||||
}
|
||||
for k, v := range re {
|
||||
column := that.MakeCodeRouter[hotimeName].TableColumns[fileConfig.GetString("table")][k]
|
||||
if column == nil {
|
||||
continue
|
||||
if that.Session(fileConfig.GetString("table")+"_id").Data == nil {
|
||||
|
||||
conf := ObjToMap(string(btes))
|
||||
delete(conf, "menus")
|
||||
delete(conf, "tables")
|
||||
//没有登录只需要返回这些信息
|
||||
that.Display(0, conf)
|
||||
return
|
||||
}
|
||||
//可读写配置
|
||||
conf := ObjToMap(string(btes))
|
||||
menus := conf.GetSlice("menus")
|
||||
|
||||
user := that.Db.Get(fileConfig.GetString("table"), "*", Map{"id": that.Session(fileConfig.GetString("table") + "_id").Data})
|
||||
|
||||
if user == nil {
|
||||
that.Display(2, "暂未登录")
|
||||
return
|
||||
}
|
||||
|
||||
for _, v := range that.MakeCodeRouter[hotimeName].TableColumns[fileConfig.GetString("table")] {
|
||||
if v.GetString("link") != "" {
|
||||
linkHasAuth := that.MakeCodeRouter[hotimeName].TableColumns[v.GetString("link")]["auth"]
|
||||
if linkHasAuth == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
linkAuthMap := that.Db.Get(v.GetString("link"), "auth", Map{"id": user.GetCeilInt(v.GetString("name"))})
|
||||
linkAuth := linkAuthMap.GetMap("auth")
|
||||
//conf := ObjToMap(string(btes))
|
||||
//menus := conf.GetSlice("menus")
|
||||
if linkAuth == nil {
|
||||
linkAuth = Map{}
|
||||
}
|
||||
|
||||
for k1, _ := range menus {
|
||||
v1 := menus.GetMap(k1)
|
||||
name := v1.GetString("name")
|
||||
if name == "" {
|
||||
name = v1.GetString("table")
|
||||
}
|
||||
if v1["auth"] != nil {
|
||||
|
||||
if linkAuth[name] == nil {
|
||||
linkAuth[name] = v1["auth"]
|
||||
} else {
|
||||
newAuth := Slice{}
|
||||
for k2, _ := range linkAuth.GetSlice(name) {
|
||||
v2 := linkAuth.GetSlice(name).GetString(k2)
|
||||
if strings.Contains(v1.GetString("auth"), v2) {
|
||||
newAuth = append(newAuth, v2)
|
||||
}
|
||||
}
|
||||
linkAuth[name] = newAuth
|
||||
}
|
||||
}
|
||||
|
||||
menusChild := v1.GetSlice("menus")
|
||||
for k2, _ := range menusChild {
|
||||
v2 := menusChild.GetMap(k2)
|
||||
name := v2.GetString("name")
|
||||
if name == "" {
|
||||
name = v2.GetString("table")
|
||||
}
|
||||
if v2["auth"] != nil {
|
||||
|
||||
if linkAuth[name] == nil {
|
||||
linkAuth[name] = v2["auth"]
|
||||
|
||||
} else {
|
||||
|
||||
newAuth := Slice{}
|
||||
for k3, _ := range linkAuth.GetSlice(name) {
|
||||
v3 := linkAuth.GetSlice(name).GetString(k3)
|
||||
if strings.Contains(v2.GetString("auth"), v3) {
|
||||
newAuth = append(newAuth, v3)
|
||||
}
|
||||
}
|
||||
linkAuth[name] = newAuth
|
||||
continue
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for k1, _ := range menus {
|
||||
v1 := menus.GetMap(k1)
|
||||
//保证个人权限可用
|
||||
if fileConfig.GetString("table") == v1.GetString("table") {
|
||||
v1["auth"] = Slice{"info", "edit"}
|
||||
}
|
||||
name := v1.GetString("name")
|
||||
if name == "" {
|
||||
name = v1.GetString("table")
|
||||
}
|
||||
|
||||
if linkAuth[name] != nil {
|
||||
v1["auth"] = linkAuth[name]
|
||||
}
|
||||
|
||||
v1menus := v1.GetSlice("menus")
|
||||
for k2, _ := range v1menus {
|
||||
v2 := v1menus.GetMap(k2)
|
||||
//保证个人权限可用
|
||||
if fileConfig.GetString("table") == v2.GetString("table") {
|
||||
v2["auth"] = Slice{"info", "edit"}
|
||||
|
||||
}
|
||||
name := v2.GetString("name")
|
||||
if name == "" {
|
||||
name = v2.GetString("table")
|
||||
}
|
||||
if linkAuth[name] != nil {
|
||||
v2["auth"] = linkAuth[name]
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
if (column["list"] == nil || column.GetBool("list")) && column.GetString("link") != "" {
|
||||
}
|
||||
|
||||
//是角色表则取下角色值
|
||||
if column.GetString("link") == "role" {
|
||||
//不可读写数据
|
||||
config := DeepCopyMap(that.MakeCodeRouter[hotimeName].Config).(Map)
|
||||
|
||||
re[column.GetString("link")] = that.Db.Get(column.GetString("link"), "id,auth,"+column.GetString("value"), Map{"id": v})
|
||||
config["menus"] = menus
|
||||
newTables := Map{}
|
||||
newTables[fileConfig.GetString("table")] = config.GetMap("tables").GetMap(fileConfig.GetString("table"))
|
||||
for k1, _ := range menus {
|
||||
v1 := menus.GetMap(k1)
|
||||
if config.GetMap("tables").GetMap(v1.GetString("table")) != nil && len(v1.GetSlice("auth")) != 0 {
|
||||
config.GetMap("tables").GetMap(v1.GetString("table"))["auth"] = Slice{}
|
||||
newTables[v1.GetString("name")] = config.GetMap("tables").GetMap(v1.GetString("table"))
|
||||
}
|
||||
v1menus := v1.GetSlice("menus")
|
||||
for k2, _ := range v1.GetSlice("menus") {
|
||||
v2 := v1menus.GetMap(k2)
|
||||
if config.GetMap("tables").GetMap(v2.GetString("table")) != nil && len(v2.GetSlice("auth")) != 0 {
|
||||
|
||||
} else {
|
||||
//有自定义配置文件
|
||||
if conf.GetMap("tables") != nil && conf.GetMap("tables").GetMap(v2.GetString("table")) != nil {
|
||||
|
||||
columns := config.GetMap("tables").GetMap(v2.GetString("table")).GetSlice("columns")
|
||||
columnsConf := conf.GetMap("tables").GetMap(v2.GetString("table")).GetSlice("columns")
|
||||
for k3, _ := range columns {
|
||||
v3 := columns.GetMap(k3)
|
||||
for k4, _ := range columnsConf {
|
||||
v4 := columnsConf.GetMap(k4)
|
||||
|
||||
if v3.GetString("name") == v4.GetString("name") {
|
||||
columns[k3] = columnsConf[k4]
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
config.GetMap("tables").GetMap(v2.GetString("table"))["auth"] = Slice{}
|
||||
newTables[v2.GetString("table")] = config.GetMap("tables").GetMap(v2.GetString("table"))
|
||||
|
||||
re[column.GetString("link")] = that.Db.Get(column.GetString("link"), "id,"+column.GetString("value"), Map{"id": v})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
that.Display(0, re)
|
||||
conf["tables"] = newTables
|
||||
|
||||
that.Display(0, conf)
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
func convertToTitle(columnNumber int) string {
|
||||
var res []byte
|
||||
for columnNumber > 0 {
|
||||
a := columnNumber % 26
|
||||
if a == 0 {
|
||||
a = 26
|
||||
}
|
||||
res = append(res, 'A'+byte(a-1))
|
||||
columnNumber = (columnNumber - a) / 26
|
||||
}
|
||||
// 上面输出的res是反着的,前后交换
|
||||
for i, n := 0, len(res); i < n/2; i++ {
|
||||
res[i], res[n-1-i] = res[n-1-i], res[i]
|
||||
}
|
||||
return string(res)
|
||||
}
|
||||
|
||||
+18
-6
@@ -5,12 +5,20 @@ import (
|
||||
)
|
||||
|
||||
var Config = Map{
|
||||
"name": "HoTimeDashBoard",
|
||||
"id": "2f92h3herh23rh2y8",
|
||||
"name": "HoTimeDashBoard",
|
||||
//"id": "2f92h3herh23rh2y8",
|
||||
"label": "HoTime管理平台",
|
||||
|
||||
"stop": Slice{"role", "org"}, //不更新的,同时不允许修改用户自身对应的表数据
|
||||
"labelConfig": Map{
|
||||
"show": "开启",
|
||||
"add": "添加",
|
||||
"delete": "删除",
|
||||
"edit": "编辑",
|
||||
"info": "查看详情",
|
||||
"download": "下载清单",
|
||||
},
|
||||
"menus": []Map{
|
||||
{"label": "平台首页", "name": "HelloWorld", "icon": "el-icon-s-home"},
|
||||
//{"label": "平台首页", "name": "HelloWorld", "icon": "el-icon-s-home"},
|
||||
//{"label": "测试表格", "table": "table", "icon": "el-icon-suitcase"},
|
||||
//{"label": "系统管理", "name": "setting", "icon": "el-icon-setting",
|
||||
// "menus": []Map{
|
||||
@@ -40,6 +48,7 @@ var ColumnDataType = map[string]string{
|
||||
"float": "number",
|
||||
"double": "number",
|
||||
"decimal": "number",
|
||||
"integer": "number", //sqlite3
|
||||
"char": "text",
|
||||
"text": "text",
|
||||
"blob": "text",
|
||||
@@ -63,9 +72,10 @@ var ColumnNameType = []ColumnShow{
|
||||
//通用
|
||||
{"idcard", false, true, true, false, "", false},
|
||||
{"id", true, false, true, false, "", true},
|
||||
{"sn", true, false, true, false, "", false},
|
||||
{"parent_ids", false, false, false, false, "index", true},
|
||||
{"parent_id", true, true, true, false, "", true},
|
||||
{"amount", true, true, true, false, "money", true},
|
||||
{"content", false, false, false, false, "textArea", false},
|
||||
{"info", false, true, true, false, "textArea", false},
|
||||
//"sn"{true,true,true,""},
|
||||
{"status", true, true, true, false, "select", false},
|
||||
@@ -79,6 +89,7 @@ var ColumnNameType = []ColumnShow{
|
||||
{"longitude", false, true, true, false, "", false},
|
||||
|
||||
{"index", false, false, false, false, "index", false},
|
||||
|
||||
{"password", false, true, false, false, "password", false},
|
||||
{"pwd", false, true, false, false, "password", false},
|
||||
|
||||
@@ -88,7 +99,7 @@ var ColumnNameType = []ColumnShow{
|
||||
{"note", false, true, true, false, "", false},
|
||||
{"description", false, true, true, false, "", false},
|
||||
{"abstract", false, true, true, false, "", false},
|
||||
{"content", false, true, true, false, "", false},
|
||||
{"content", false, true, true, false, "textArea", false},
|
||||
{"address", true, true, true, false, "", false},
|
||||
{"full_name", false, true, true, false, "", false},
|
||||
{"create_time", false, false, true, false, "time", true},
|
||||
@@ -103,6 +114,7 @@ var ColumnNameType = []ColumnShow{
|
||||
{"time", true, true, true, false, "time", false},
|
||||
{"level", false, false, true, false, "", false},
|
||||
{"rule", true, true, true, false, "form", false},
|
||||
{"auth", false, true, true, false, "auth", true},
|
||||
{"table", true, false, true, false, "table", false},
|
||||
{"table_id", true, false, true, false, "table_id", false},
|
||||
}
|
||||
|
||||
+296
-151
@@ -27,6 +27,7 @@ type MakeCode struct {
|
||||
|
||||
func (that *MakeCode) Db2JSON(db *db.HoTimeDB, config Map) {
|
||||
isMake := false
|
||||
//hasConfigFile := false
|
||||
idSlice := Slice{}
|
||||
that.FileConfig = config
|
||||
if that.TableColumns == nil {
|
||||
@@ -37,22 +38,25 @@ func (that *MakeCode) Db2JSON(db *db.HoTimeDB, config Map) {
|
||||
}
|
||||
|
||||
//加载配置文件
|
||||
btes, err := ioutil.ReadFile(config.GetString("config"))
|
||||
|
||||
//btes, err := ioutil.ReadFile(config.GetString("config"))
|
||||
var err error
|
||||
that.Config = DeepCopyMap(Config).(Map)
|
||||
|
||||
that.Config["name"] = config.GetString("table")
|
||||
if err == nil {
|
||||
cmap := Map{}
|
||||
//文件是否损坏
|
||||
cmap.JsonToMap(string(btes), &that.Error)
|
||||
for k, v := range cmap {
|
||||
that.Config[k] = v //程序配置
|
||||
//Config[k] = v //系统配置
|
||||
}
|
||||
} else {
|
||||
that.Error.SetError(errors.New("config配置文件不存在,或者配置出错,使用缺省默认配置"))
|
||||
}
|
||||
//if err == nil {
|
||||
// cmap := Map{}
|
||||
// //文件是否损坏
|
||||
// cmap.JsonToMap(string(btes), &that.Error)
|
||||
// for k, v := range cmap {
|
||||
// that.Config[k] = v //程序配置
|
||||
// //Config[k] = v //系统配置
|
||||
// }
|
||||
// hasConfigFile = true
|
||||
//} else {
|
||||
//
|
||||
// that.Error.SetError(errors.New("config配置文件不存在,或者配置出错,使用缺省默认配置"))
|
||||
//
|
||||
//}
|
||||
//加载规则文件
|
||||
btesRule, errRule := ioutil.ReadFile(config.GetString("rule"))
|
||||
that.RuleConfig = []Map{}
|
||||
@@ -80,38 +84,6 @@ func (that *MakeCode) Db2JSON(db *db.HoTimeDB, config Map) {
|
||||
}
|
||||
|
||||
that.IndexMenus = Map{}
|
||||
menusConfig := that.Config.GetSlice("menus")
|
||||
//将配置写入到内存中仅作为判断用
|
||||
if menusConfig != nil {
|
||||
for kmenu, _ := range menusConfig {
|
||||
menu := menusConfig.GetMap(kmenu)
|
||||
if menu != nil {
|
||||
mname := menu.GetString("table")
|
||||
if mname == "" { //如果为空则不是表格
|
||||
mname = menu.GetString("name")
|
||||
}
|
||||
that.IndexMenus[mname] = menu
|
||||
childMenus := menu.GetSlice("menus")
|
||||
if childMenus != nil {
|
||||
for ckmenu, _ := range childMenus {
|
||||
cmenu := childMenus.GetMap(ckmenu)
|
||||
if cmenu != nil {
|
||||
cname := cmenu.GetString("table")
|
||||
if cmenu.GetString("table") == "" {
|
||||
continue
|
||||
}
|
||||
that.IndexMenus[mname+"/"+cname] = cmenu
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
that.TableConfig = that.Config.GetMap("tables")
|
||||
if that.TableConfig == nil {
|
||||
that.TableConfig = Map{}
|
||||
@@ -172,7 +144,7 @@ func (that *MakeCode) Db2JSON(db *db.HoTimeDB, config Map) {
|
||||
that.TableConfig[v.GetString("name")] = Map{
|
||||
"label": v.GetString("label"),
|
||||
"table": v.GetString("name"),
|
||||
"auth": []string{"show", "add", "delete", "edit", "info"},
|
||||
"auth": []string{"show", "add", "delete", "edit", "info", "download"},
|
||||
"columns": []Map{},
|
||||
"search": []Map{
|
||||
|
||||
@@ -181,6 +153,10 @@ func (that *MakeCode) Db2JSON(db *db.HoTimeDB, config Map) {
|
||||
{"type": "search", "name": "sort", "label": "排序", "value": nil},
|
||||
},
|
||||
}
|
||||
|
||||
if v.GetString("name") == "logs" {
|
||||
that.TableConfig.GetMap(v.GetString("name"))["auth"] = []string{"show", "download"}
|
||||
}
|
||||
}
|
||||
|
||||
//初始化
|
||||
@@ -313,13 +289,6 @@ func (that *MakeCode) Db2JSON(db *db.HoTimeDB, config Map) {
|
||||
//}
|
||||
|
||||
}
|
||||
//else {
|
||||
//
|
||||
// //if !(coloum.GetString("label") != "备注" && info.GetString("label") == "备注") {
|
||||
// // coloum["label"] = info.GetString("label")
|
||||
// //}
|
||||
// //coloum["type"] = info.GetString("type")
|
||||
//}
|
||||
|
||||
//暂时不关闭参数,保证表数据完全读取到
|
||||
that.TableColumns[v.GetString("name")][info.GetString("name")] = coloum
|
||||
@@ -352,83 +321,84 @@ func (that *MakeCode) Db2JSON(db *db.HoTimeDB, config Map) {
|
||||
|
||||
//生成id,判断数据库是否有改变,以保证数据库和配置文件匹配唯一
|
||||
id := Md5(ObjToStr(idSlice))
|
||||
if id == that.Config.GetString("id") {
|
||||
if isMake { //有生成包文件
|
||||
fmt.Println("有新的业务代码生成,请重新运行")
|
||||
os.Exit(-1)
|
||||
}
|
||||
//if id == that.Config.GetString("id") {
|
||||
if isMake { //有生成包文件
|
||||
fmt.Println("有新的业务代码生成,请重新运行")
|
||||
os.Exit(-1)
|
||||
return
|
||||
}
|
||||
|
||||
//}
|
||||
//数据生成完后进一步解析
|
||||
for fk, fv := range that.TableColumns {
|
||||
|
||||
//判断是否将表写入menu中
|
||||
isMenusGet := false //判断是否被目录收录
|
||||
for indexKey, _ := range that.IndexMenus {
|
||||
indexCode := strings.Index(indexKey, fk)
|
||||
if indexCode == 0 || indexCode == 4 {
|
||||
isMenusGet = false
|
||||
continue
|
||||
}
|
||||
//如果相等或者表名在目录中已经设置(主要前一位是/并且他是最后一个字符串)
|
||||
if indexKey == fk || (indexCode != -1 && indexKey[indexCode-1] == '/' && indexKey[indexCode:] == fk) {
|
||||
isMenusGet = true
|
||||
//isMenusGet := false //判断是否被目录收录
|
||||
//for indexKey, _ := range that.IndexMenus {
|
||||
// indexCode := strings.Index(indexKey, fk)
|
||||
// if indexCode == 0 || indexCode == 4 {
|
||||
// isMenusGet = false
|
||||
// continue
|
||||
// }
|
||||
// //如果相等或者表名在目录中已经设置(主要前一位是/并且他是最后一个字符串)
|
||||
// if indexKey == fk || (indexCode != -1 && indexKey[indexCode-1] == '/' && indexKey[indexCode:] == fk) {
|
||||
// isMenusGet = true
|
||||
// break
|
||||
// }
|
||||
//}
|
||||
|
||||
//目录没有收录
|
||||
//if !isMenusGet {
|
||||
//if !hasConfigFile {
|
||||
tablePrefixCode := strings.Index(fk, "_")
|
||||
isNewPrefix := false //假定表名没有前缀
|
||||
prefixName := ""
|
||||
//并且代表有前缀,根据数据表分库设定使用
|
||||
if tablePrefixCode != -1 {
|
||||
prefixName = fk[:tablePrefixCode]
|
||||
} else {
|
||||
prefixName = fk
|
||||
}
|
||||
//if tablePrefixCode != -1 {
|
||||
for ck, _ := range that.TableColumns {
|
||||
//判断不止一个前缀相同
|
||||
if (strings.Index(ck, prefixName) == 0 || strings.Index(prefixName, ck) == 4) && ck != fk {
|
||||
isNewPrefix = true
|
||||
break
|
||||
}
|
||||
}
|
||||
//}
|
||||
|
||||
//目录没有收录
|
||||
if !isMenusGet {
|
||||
prefixName = DefaultMenuParentName + ":" + prefixName
|
||||
|
||||
tablePrefixCode := strings.Index(fk, "_")
|
||||
isNewPrefix := false //假定表名没有前缀
|
||||
prefixName := ""
|
||||
//并且代表有前缀,根据数据表分库设定使用
|
||||
if tablePrefixCode != -1 {
|
||||
prefixName = fk[:tablePrefixCode]
|
||||
} else {
|
||||
prefixName = fk
|
||||
}
|
||||
//if tablePrefixCode != -1 {
|
||||
for ck, _ := range that.TableColumns {
|
||||
//判断不止一个前缀相同
|
||||
if (strings.Index(ck, prefixName) == 0 || strings.Index(prefixName, ck) == 4) && ck != fk {
|
||||
isNewPrefix = true
|
||||
break
|
||||
}
|
||||
}
|
||||
//}
|
||||
|
||||
prefixName = DefaultMenuParentName + ":" + prefixName
|
||||
|
||||
menuIns := Map{"label": that.TableConfig.GetMap(fk).GetString("label"), "table": fk}
|
||||
//多耗费一点内存
|
||||
mMenu := Map{"menus": Slice{menuIns}, "label": that.TableConfig.GetMap(fk).GetString("label"), "name": prefixName, "icon": "el-icon-setting"}
|
||||
//表名有前缀
|
||||
if !isNewPrefix {
|
||||
//是否已有对应前缀,已经有对应的menu只需要push进去即可
|
||||
prefixName = DefaultMenuParentName
|
||||
mMenu = Map{"menus": Slice{menuIns}, "label": "系统管理", "name": prefixName, "icon": "el-icon-setting"}
|
||||
}
|
||||
//没有新前缀
|
||||
if that.IndexMenus[prefixName] != nil {
|
||||
if that.IndexMenus[prefixName+"/"+fk] == nil {
|
||||
that.IndexMenus.GetMap(prefixName)["menus"] = append(that.IndexMenus.GetMap(prefixName).GetSlice("menus"), menuIns)
|
||||
that.IndexMenus[prefixName+"/"+fk] = menuIns
|
||||
} else {
|
||||
for k, v := range menuIns {
|
||||
that.IndexMenus.GetMap(prefixName + "/" + fk)[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
that.Config["menus"] = append(that.Config.GetSlice("menus"), mMenu) //注入配置
|
||||
//写入Index
|
||||
that.IndexMenus[prefixName] = mMenu
|
||||
that.IndexMenus[prefixName+"/"+fk] = menuIns
|
||||
}
|
||||
menuIns := Map{"label": that.TableConfig.GetMap(fk).GetString("label"), "table": fk, "auth": that.TableConfig.GetMap(fk).GetSlice("auth")}
|
||||
//多耗费一点内存
|
||||
mMenu := Map{"menus": Slice{menuIns}, "auth": Slice{"show"}, "label": that.TableConfig.GetMap(fk).GetString("label"), "name": prefixName, "icon": "el-icon-setting"}
|
||||
//表名有前缀
|
||||
if !isNewPrefix {
|
||||
//是否已有对应前缀,已经有对应的menu只需要push进去即可
|
||||
prefixName = DefaultMenuParentName
|
||||
mMenu = Map{"menus": Slice{menuIns}, "auth": Slice{"show"}, "label": "系统管理", "name": prefixName, "icon": "el-icon-setting"}
|
||||
}
|
||||
//没有新前缀
|
||||
if that.IndexMenus[prefixName] != nil {
|
||||
if that.IndexMenus[prefixName+"/"+fk] == nil {
|
||||
that.IndexMenus.GetMap(prefixName)["menus"] = append(that.IndexMenus.GetMap(prefixName).GetSlice("menus"), menuIns)
|
||||
that.IndexMenus[prefixName+"/"+fk] = menuIns
|
||||
} else {
|
||||
for k, v := range menuIns {
|
||||
that.IndexMenus.GetMap(prefixName + "/" + fk)[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
that.Config["menus"] = append(that.Config.GetSlice("menus"), mMenu) //注入配置
|
||||
//写入Index
|
||||
that.IndexMenus[prefixName] = mMenu
|
||||
that.IndexMenus[prefixName+"/"+fk] = menuIns
|
||||
}
|
||||
//}
|
||||
|
||||
for k, v := range fv {
|
||||
|
||||
@@ -541,18 +511,21 @@ func (that *MakeCode) Db2JSON(db *db.HoTimeDB, config Map) {
|
||||
search := that.TableConfig.GetMap(fk).GetSlice("search")
|
||||
sv := Map{"type": "tree", "label": v["label"], "name": v["name"], "value": v["value"], "link": v["link"]}
|
||||
that.TableConfig.GetMap(fk)["search"] = append(search, sv)
|
||||
|
||||
that.SearchColumns[fk][k] = sv
|
||||
}
|
||||
|
||||
if fk == that.FileConfig.GetString("table") && v["link"] != nil && that.TableColumns[v.GetString("link")]["parent_id"] != nil {
|
||||
that.Config["stop"] = append(that.Config.GetSlice("stop"), v.GetString("link"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fmt.Println(id, "---", that.Config.GetString("id"))
|
||||
that.Config["id"] = id
|
||||
//fmt.Println(id, "---", that.Config.GetString("id"))
|
||||
//that.Config["id"] = id
|
||||
|
||||
if config.GetInt("mode") != 0 {
|
||||
//init文件初始化
|
||||
myInit = strings.Replace(myInit, "{{id}}", id, -1)
|
||||
//myInit = strings.Replace(myInit, "{{id}}", id, -1)
|
||||
myInit = strings.Replace(myInit, "{{tablesCtr}}", ctrList, -1)
|
||||
_ = os.MkdirAll(config.GetString("name"), os.ModeDir)
|
||||
err = ioutil.WriteFile(config.GetString("name")+"/init.go", []byte(myInit), os.ModePerm)
|
||||
@@ -561,16 +534,36 @@ func (that *MakeCode) Db2JSON(db *db.HoTimeDB, config Map) {
|
||||
}
|
||||
}
|
||||
|
||||
//写入配置文件
|
||||
//err = json.Indent(&configByte, []byte(that.Config.ToJsonString()), "", "\t")
|
||||
_ = os.MkdirAll(filepath.Dir(config.GetString("config")), os.ModeDir)
|
||||
err = ioutil.WriteFile(config.GetString("config"), []byte(that.Config.ToJsonString()), os.ModePerm)
|
||||
if err != nil {
|
||||
that.Error.SetError(err)
|
||||
//配置文件
|
||||
if config.GetString("configDB") != "" {
|
||||
|
||||
that.Config["id"] = id
|
||||
_ = os.MkdirAll(filepath.Dir(config.GetString("configDB")), os.ModeDir)
|
||||
err = ioutil.WriteFile(config.GetString("configDB"), []byte(that.Config.ToJsonString()), os.ModePerm)
|
||||
if err != nil {
|
||||
that.Error.SetError(err)
|
||||
}
|
||||
that.Logger.Warn("新建")
|
||||
|
||||
}
|
||||
|
||||
fmt.Println("有新的代码生成,请重新运行")
|
||||
os.Exit(-1)
|
||||
//不存在配置文件则生成,存在则不管
|
||||
_, err = ioutil.ReadFile(config.GetString("config"))
|
||||
if err != nil {
|
||||
|
||||
that.Config["id"] = id
|
||||
_ = os.MkdirAll(filepath.Dir(config.GetString("config")), os.ModeDir)
|
||||
newConfig := DeepCopyMap(that.Config).(Map)
|
||||
delete(newConfig, "tables")
|
||||
err = ioutil.WriteFile(config.GetString("config"), []byte(newConfig.ToJsonString()), os.ModePerm)
|
||||
if err != nil {
|
||||
that.Error.SetError(err)
|
||||
}
|
||||
that.Logger.Warn("新建")
|
||||
|
||||
}
|
||||
//fmt.Println("有新的代码生成,请重新运行")
|
||||
//os.Exit(-1)
|
||||
|
||||
}
|
||||
|
||||
@@ -608,11 +601,21 @@ func (that *MakeCode) Info(table string, userData Map, db *db.HoTimeDB) (string,
|
||||
}
|
||||
if ruleData[v.GetString("link")] != nil {
|
||||
|
||||
parent_idsStr := ""
|
||||
parent_ids := that.TableColumns[v.GetString("link")]["parent_ids"]
|
||||
if parent_ids != nil {
|
||||
parent_idsStr = "parent_ids[~]"
|
||||
}
|
||||
index := that.TableColumns[v.GetString("link")]["index"]
|
||||
if index != nil {
|
||||
parent_idsStr = "index[~]"
|
||||
}
|
||||
|
||||
if v.GetString("name") == "parent_id" {
|
||||
data["index[~]"] = "," + ruleData.GetString(v.GetString("link")) + ","
|
||||
data[parent_idsStr] = "," + ruleData.GetString(v.GetString("link")) + ","
|
||||
|
||||
} else {
|
||||
idMap := db.Select(v.GetString("link"), "id", Map{"index[~]": "," + ruleData.GetString(v.GetString("link")) + ","})
|
||||
idMap := db.Select(v.GetString("link"), "id", Map{parent_idsStr: "," + ruleData.GetString(v.GetString("link")) + ","})
|
||||
ids := Slice{ruleData.GetCeilInt(v.GetString("link"))}
|
||||
for _, v := range idMap {
|
||||
ids = append(ids, v.GetCeilInt("id"))
|
||||
@@ -645,9 +648,9 @@ func (that *MakeCode) Add(table string, user Map, req *http.Request) Map {
|
||||
}
|
||||
if v.Get("add") == nil || v.GetBool("add") {
|
||||
|
||||
if len(req.Form[v.GetString("name")]) == 0 {
|
||||
if len(req.Form[v.GetString("name")]) == 0 || req.FormValue(v.GetString("name")) == "" {
|
||||
|
||||
if user[v.GetString("name")] != nil {
|
||||
if v["link"] != nil && user[v.GetString("name")] != nil {
|
||||
data[v.GetString("name")] = user[v.GetString("name")]
|
||||
continue
|
||||
}
|
||||
@@ -657,6 +660,13 @@ func (that *MakeCode) Add(table string, user Map, req *http.Request) Map {
|
||||
continue
|
||||
}
|
||||
|
||||
if user[v.GetString("name")] != nil {
|
||||
|
||||
data[v.GetString("name")] = user[v.GetString("name")]
|
||||
continue
|
||||
|
||||
}
|
||||
|
||||
if v.GetBool("must") {
|
||||
return nil
|
||||
} else {
|
||||
@@ -664,6 +674,7 @@ func (that *MakeCode) Add(table string, user Map, req *http.Request) Map {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
reqValue := req.FormValue(v.GetString("name"))
|
||||
if (reqValue == "" || reqValue == "null") && strings.Contains(v.GetString("name"), "id") {
|
||||
data[v.GetString("name")] = nil
|
||||
@@ -676,7 +687,16 @@ func (that *MakeCode) Add(table string, user Map, req *http.Request) Map {
|
||||
|
||||
}
|
||||
}
|
||||
//sn则自动生成
|
||||
if v.GetString("name") == "sn" {
|
||||
reqValue := req.FormValue(v.GetString("name"))
|
||||
if reqValue == "" {
|
||||
data[v.GetString("name")] = Md5(ObjToStr(time.Now().UnixNano()))
|
||||
} else {
|
||||
data[v.GetString("name")] = reqValue
|
||||
}
|
||||
|
||||
}
|
||||
if v.GetString("name") == "create_time" {
|
||||
if v.GetString("type") == "unixTime" {
|
||||
data[v.GetString("name")] = time.Now().Unix()
|
||||
@@ -724,8 +744,14 @@ func (that *MakeCode) Edit(table string, req *http.Request) Map {
|
||||
data[v.GetString("name")] = reqValue
|
||||
}
|
||||
}
|
||||
|
||||
if v.GetString("name") == "modify_time" {
|
||||
data[v.GetString("name")] = time.Now().Unix()
|
||||
if v.GetString("type") == "unixTime" {
|
||||
data[v.GetString("name")] = time.Now().Unix()
|
||||
}
|
||||
if v.GetString("type") == "time" {
|
||||
data[v.GetString("name")] = time.Now().Format("2006-01-02 15-04-05")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -777,6 +803,7 @@ func (that *MakeCode) Search(table string, userData Map, req *http.Request, db *
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if v["list"] != false {
|
||||
|
||||
if v.GetString("link") != "" &&
|
||||
@@ -809,9 +836,17 @@ func (that *MakeCode) Search(table string, userData Map, req *http.Request, db *
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
reStr += table + "." + v.GetString("name") + ","
|
||||
}
|
||||
|
||||
if v["name"] == "parent_id" && v.GetString("link") != "" {
|
||||
leftJoin["[>]"+v.GetString("link")+" selfParent"] =
|
||||
"selfParent.id=" +
|
||||
v.GetString("link") + "." + v.GetString("name")
|
||||
reStr += "selfParent." + v.GetString("value") + " AS " + v.GetString("link") + "_" + v.GetString("name") + "_" + v.GetString("value") + ","
|
||||
}
|
||||
|
||||
//准备加入索引权限
|
||||
if v.GetString("link") != "" &&
|
||||
userData != nil &&
|
||||
@@ -828,12 +863,22 @@ func (that *MakeCode) Search(table string, userData Map, req *http.Request, db *
|
||||
}
|
||||
}
|
||||
if ruleData[v.GetString("link")] != nil {
|
||||
parent_idsStr := ""
|
||||
parent_ids := that.TableColumns[v.GetString("link")]["parent_ids"]
|
||||
if parent_ids != nil {
|
||||
parent_idsStr = "parent_ids[~]"
|
||||
}
|
||||
index := that.TableColumns[v.GetString("link")]["index"]
|
||||
if index != nil {
|
||||
parent_idsStr = "index[~]"
|
||||
}
|
||||
|
||||
if v.GetString("name") == "parent_id" {
|
||||
data[table+".index[~]"] = "," + ruleData.GetString(v.GetString("link")) + ","
|
||||
|
||||
data[table+"."+parent_idsStr] = "," + ruleData.GetString(v.GetString("link")) + ","
|
||||
|
||||
} else {
|
||||
idMap := db.Select(v.GetString("link"), "id", Map{"index[~]": "," + ruleData.GetString(v.GetString("link")) + ","})
|
||||
idMap := db.Select(v.GetString("link"), "id", Map{parent_idsStr: "," + ruleData.GetString(v.GetString("link")) + ","})
|
||||
ids := Slice{ruleData.GetCeilInt(v.GetString("link"))}
|
||||
for _, v := range idMap {
|
||||
ids = append(ids, v.GetCeilInt("id"))
|
||||
@@ -845,6 +890,38 @@ func (that *MakeCode) Search(table string, userData Map, req *http.Request, db *
|
||||
|
||||
}
|
||||
|
||||
if v.GetString("type") == "text" {
|
||||
reqValue := req.FormValue(v.GetString("name"))
|
||||
if reqValue != "" {
|
||||
data[table+"."+v.GetString("name")+"[~]"] = reqValue
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if v.GetString("type") == "unixtime" {
|
||||
//fmt.Println(req.Form["daterange"])
|
||||
if len(req.Form[v.GetString("name")]) == 1 {
|
||||
daterange[table+"."+v.GetString("name")+"[>]"] = req.FormValue("daterange")
|
||||
} else if len(req.Form[v.GetString("name")]) == 2 {
|
||||
daterange[table+"."+v.GetString("name")+"[<>]"] = ObjToSlice(req.Form["daterange"])
|
||||
}
|
||||
}
|
||||
|
||||
if v.GetString("type") == "time" {
|
||||
//fmt.Println(req.Form["daterange"])
|
||||
|
||||
if len(req.Form[v.GetString("name")]) == 1 {
|
||||
t := time.Unix(ObjToCeilInt64(req.FormValue(v.GetString("name"))), 0).Format("2006-01-02 15:04:05")
|
||||
|
||||
daterange[table+"."+v.GetString("name")+"[>]"] = t
|
||||
|
||||
} else if len(req.Form[v.GetString("name")]) == 2 {
|
||||
t1 := time.Unix(ObjToCeilInt64(req.Form[v.GetString("name")][0]), 0).Format("2006-01-02 15:04:05")
|
||||
t2 := time.Unix(ObjToCeilInt64(req.Form[v.GetString("name")][1]), 0).Format("2006-01-02 15:04:05")
|
||||
daterange[table+"."+v.GetString("name")+"[<>]"] = Slice{t1, t2}
|
||||
}
|
||||
}
|
||||
|
||||
if keywordStr != "" {
|
||||
if v.GetString("type") == "text" {
|
||||
keyword[table+"."+v.GetString("name")+"[~]"] = keywordStr
|
||||
@@ -875,13 +952,37 @@ func (that *MakeCode) Search(table string, userData Map, req *http.Request, db *
|
||||
|
||||
search := that.TableConfig.GetMap(table).GetSlice("search")
|
||||
for k, _ := range search {
|
||||
|
||||
reqValue := req.FormValue(search.GetMap(k).GetString("name"))
|
||||
if reqValue == "" {
|
||||
continue
|
||||
}
|
||||
searchItem := search.GetMap(k)
|
||||
searchItemName := searchItem.GetString("name")
|
||||
parent_idsStr := ""
|
||||
parent_ids := that.TableColumns[searchItem.GetString("link")]["parent_ids"]
|
||||
if parent_ids != nil {
|
||||
parent_idsStr = "parent_ids[~]"
|
||||
}
|
||||
index := that.TableColumns[searchItem.GetString("link")]["index"]
|
||||
if index != nil {
|
||||
parent_idsStr = "index[~]"
|
||||
}
|
||||
|
||||
reqValue := req.Form[search.GetMap(k).GetString("name")]
|
||||
|
||||
//reqValue := req.FormValue(search.GetMap(k).GetString("name"))
|
||||
if len(reqValue) == 0 || reqValue[0] == "" {
|
||||
|
||||
if parent_idsStr != "" && userData[searchItem.GetString("name")] != nil {
|
||||
where := Map{parent_idsStr: "," + ObjToStr(userData.GetCeilInt64(searchItem.GetString("name"))) + ","}
|
||||
r := db.Select(searchItem.GetString("link"), "id", where)
|
||||
reqValue = []string{}
|
||||
for _, v := range r {
|
||||
reqValue = append(reqValue, v.GetString("id"))
|
||||
}
|
||||
|
||||
data[table+"."+searchItemName] = reqValue
|
||||
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
//columns := that.TableConfig.GetMap(table).GetSlice("columns")
|
||||
if searchItem.GetString("type") == "search" {
|
||||
@@ -894,7 +995,7 @@ func (that *MakeCode) Search(table string, userData Map, req *http.Request, db *
|
||||
if v.GetString("type") == "unixtime" {
|
||||
//fmt.Println(req.Form["daterange"])
|
||||
if len(req.Form["daterange"]) == 1 {
|
||||
daterange[table+"."+v.GetString("name")+"[<]"] = req.FormValue("daterange")
|
||||
daterange[table+"."+v.GetString("name")+"[>]"] = req.FormValue("daterange")
|
||||
} else if len(req.Form["daterange"]) == 2 {
|
||||
|
||||
daterange[table+"."+v.GetString("name")+"[<>]"] = ObjToSlice(req.Form["daterange"])
|
||||
@@ -906,7 +1007,7 @@ func (that *MakeCode) Search(table string, userData Map, req *http.Request, db *
|
||||
if len(req.Form["daterange"]) == 1 {
|
||||
t := time.Unix(ObjToCeilInt64(req.FormValue("daterange")), 0).Format("2006-01-02 15:04:05")
|
||||
|
||||
daterange[table+"."+v.GetString("name")+"[<]"] = t
|
||||
daterange[table+"."+v.GetString("name")+"[>]"] = t
|
||||
|
||||
} else if len(req.Form["daterange"]) == 2 {
|
||||
t1 := time.Unix(ObjToCeilInt64(req.Form["daterange"][0]), 0).Format("2006-01-02 15:04:05")
|
||||
@@ -919,26 +1020,74 @@ func (that *MakeCode) Search(table string, userData Map, req *http.Request, db *
|
||||
}
|
||||
|
||||
if searchItem.GetString("name") == "sort" {
|
||||
sortMap["ORDER"] = table + "." + reqValue
|
||||
sortMap["ORDER"] = table + "." + reqValue[0]
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
//树节点模式搜索
|
||||
if searchItemName == "parent_id" {
|
||||
//if parent_idsStr != "" {
|
||||
//
|
||||
// where := Map{}
|
||||
//
|
||||
// for _, v := range reqValue {
|
||||
// if len(where) == 0 {
|
||||
// where[parent_idsStr] = "," + v + ","
|
||||
// continue
|
||||
// }
|
||||
// where = Map{"OR": where, parent_idsStr: "," + v + ","}
|
||||
// }
|
||||
// //用户
|
||||
// if userData[searchItem.GetString("name")] != nil {
|
||||
// where = Map{"AND": Map{parent_idsStr: "," + ObjToStr(userData.GetCeilInt64(searchItem.GetString("name"))) + ",", "OR": where}}
|
||||
// }
|
||||
// r := db.Select(searchItem.GetString("link"), "id", where)
|
||||
// for _, v := range r {
|
||||
// reqValue = append(reqValue, v.GetString("id"))
|
||||
// }
|
||||
//
|
||||
//}
|
||||
|
||||
parentID := ObjToInt(req.FormValue("parent_id"))
|
||||
if parentID == 0 {
|
||||
parentID = userData.GetCeilInt(table + "_id")
|
||||
data["OR"] = Map{table + ".id": parentID, table + ".parent_id": nil}
|
||||
} else {
|
||||
data[table+".parent_id"] = parentID
|
||||
data[table+".parent_id"] = reqValue
|
||||
}
|
||||
continue
|
||||
}
|
||||
//如果是树节点则需要判断是否符合权限
|
||||
if searchItem.GetString("type") == "tree" {
|
||||
|
||||
if parent_idsStr != "" {
|
||||
|
||||
where := Map{}
|
||||
|
||||
for _, v := range reqValue {
|
||||
if len(where) == 0 {
|
||||
where[parent_idsStr] = "," + v + ","
|
||||
continue
|
||||
}
|
||||
where = Map{"OR": where, parent_idsStr: "," + v + ","}
|
||||
}
|
||||
//用户
|
||||
if userData[searchItem.GetString("name")] != nil {
|
||||
where = Map{"AND": Map{parent_idsStr: "," + ObjToStr(userData.GetCeilInt64(searchItem.GetString("name"))) + ",", "OR": where}}
|
||||
}
|
||||
r := db.Select(searchItem.GetString("link"), "id", where)
|
||||
for _, v := range r {
|
||||
reqValue = append(reqValue, v.GetString("id"))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
data[table+"."+searchItemName] = reqValue
|
||||
|
||||
}
|
||||
|
||||
if sortMap["ORDER"] == nil {
|
||||
sortMap["ORDER"] = table + ".id DESC"
|
||||
}
|
||||
@@ -995,7 +1144,3 @@ func (that *MakeCode) Search(table string, userData Map, req *http.Request, db *
|
||||
|
||||
return reStr, leftJoin, where
|
||||
}
|
||||
|
||||
func setListener() {
|
||||
|
||||
}
|
||||
|
||||
+1
-1
@@ -102,7 +102,7 @@ func (that Map) GetBool(key string, err ...*Error) bool {
|
||||
|
||||
}
|
||||
|
||||
func (that Map) GetTime(key string, err ...*Error) time.Time {
|
||||
func (that Map) GetTime(key string, err ...*Error) *time.Time {
|
||||
|
||||
v := ObjToTime((that)[key], err...)
|
||||
return v
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ func (that *Obj) ToInt(err ...Error) int {
|
||||
return ObjToInt(that.Data, &that.Error)
|
||||
}
|
||||
|
||||
func (that *Obj) ToTime(err ...Error) time.Time {
|
||||
func (that *Obj) ToTime(err ...Error) *time.Time {
|
||||
if len(err) != 0 {
|
||||
that.Error = err[0]
|
||||
}
|
||||
|
||||
+16
-13
@@ -97,7 +97,7 @@ func ObjToSlice(obj interface{}, e ...*Error) Slice {
|
||||
return v
|
||||
}
|
||||
|
||||
func ObjToTime(obj interface{}, e ...*Error) time.Time {
|
||||
func ObjToTime(obj interface{}, e ...*Error) *time.Time {
|
||||
|
||||
tInt := ObjToInt64(obj)
|
||||
//字符串类型,只支持标准mysql datetime格式
|
||||
@@ -107,27 +107,27 @@ func ObjToTime(obj interface{}, e ...*Error) time.Time {
|
||||
if len(tStr) > 18 {
|
||||
t, e := time.Parse("2006-01-02 15:04:05", tStr)
|
||||
if e == nil {
|
||||
return t
|
||||
return &t
|
||||
}
|
||||
} else if len(tStr) > 15 {
|
||||
t, e := time.Parse("2006-01-02 15:04", tStr)
|
||||
if e == nil {
|
||||
return t
|
||||
return &t
|
||||
}
|
||||
} else if len(tStr) > 12 {
|
||||
t, e := time.Parse("2006-01-02 15", tStr)
|
||||
if e == nil {
|
||||
return t
|
||||
return &t
|
||||
}
|
||||
} else if len(tStr) > 9 {
|
||||
t, e := time.Parse("2006-01-02", tStr)
|
||||
if e == nil {
|
||||
return t
|
||||
return &t
|
||||
}
|
||||
} else if len(tStr) > 6 {
|
||||
t, e := time.Parse("2006-01", tStr)
|
||||
if e == nil {
|
||||
return t
|
||||
return &t
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,25 +135,28 @@ func ObjToTime(obj interface{}, e ...*Error) time.Time {
|
||||
|
||||
//纳秒级别
|
||||
if len(ObjToStr(tInt)) > 16 {
|
||||
|
||||
return time.Time{}.Add(time.Nanosecond * time.Duration(tInt))
|
||||
t := time.Time{}.Add(time.Nanosecond * time.Duration(tInt))
|
||||
return &t
|
||||
//微秒级别
|
||||
} else if len(ObjToStr(tInt)) > 13 {
|
||||
return time.Time{}.Add(time.Microsecond * time.Duration(tInt))
|
||||
t := time.Time{}.Add(time.Microsecond * time.Duration(tInt))
|
||||
return &t
|
||||
//毫秒级别
|
||||
} else if len(ObjToStr(tInt)) > 10 {
|
||||
return time.Time{}.Add(time.Millisecond * time.Duration(tInt))
|
||||
t := time.Time{}.Add(time.Millisecond * time.Duration(tInt))
|
||||
return &t
|
||||
//秒级别
|
||||
} else if len(ObjToStr(tInt)) > 9 {
|
||||
return time.Time{}.Add(time.Second * time.Duration(tInt))
|
||||
t := time.Time{}.Add(time.Second * time.Duration(tInt))
|
||||
return &t
|
||||
} else if len(ObjToStr(tInt)) > 3 {
|
||||
t, e := time.Parse("2006", ObjToStr(tInt))
|
||||
if e == nil {
|
||||
return t
|
||||
return &t
|
||||
}
|
||||
}
|
||||
|
||||
return time.Time{}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ObjToFloat64(obj interface{}, e ...*Error) float64 {
|
||||
|
||||
+1
-1
@@ -15,7 +15,7 @@ func (that Slice) GetString(key int, err ...*Error) string {
|
||||
return ObjToStr((that)[key])
|
||||
}
|
||||
|
||||
func (that Slice) GetTime(key int, err ...*Error) time.Time {
|
||||
func (that Slice) GetTime(key int, err ...*Error) *time.Time {
|
||||
|
||||
v := ObjToTime((that)[key], err...)
|
||||
return v
|
||||
|
||||
+2
-3
@@ -1,7 +1,6 @@
|
||||
package hotime
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime/cache"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
. "code.hoteas.com/golang/hotime/db"
|
||||
"encoding/json"
|
||||
@@ -19,7 +18,7 @@ type Context struct {
|
||||
Db *HoTimeDB
|
||||
RespData Map
|
||||
RespFunc func()
|
||||
CacheIns
|
||||
//CacheIns
|
||||
SessionIns
|
||||
DataSize int
|
||||
HandlerStr string //复写请求url
|
||||
@@ -68,7 +67,7 @@ func (that *Context) View() {
|
||||
}
|
||||
//创建日志
|
||||
if that.Log != nil {
|
||||
that.Log["time"] = time.Now().Unix()
|
||||
that.Log["time"] = time.Now().Format("2006-01-02 15:04")
|
||||
if that.Session("admin_id").Data != nil {
|
||||
that.Log["admin_id"] = that.Session("admin_id").ToCeilInt()
|
||||
}
|
||||
|
||||
+401
-111
@@ -8,6 +8,7 @@ import (
|
||||
"errors"
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
"github.com/sirupsen/logrus"
|
||||
"os"
|
||||
"reflect"
|
||||
"sort"
|
||||
@@ -19,6 +20,7 @@ type HoTimeDB struct {
|
||||
ContextBase
|
||||
DBName string
|
||||
*cache.HoTimeCache
|
||||
Log *logrus.Logger
|
||||
Type string
|
||||
Prefix string
|
||||
LastQuery string
|
||||
@@ -28,6 +30,231 @@ type HoTimeDB struct {
|
||||
limit Slice
|
||||
*sql.Tx //事务对象
|
||||
SlaveDB *sql.DB
|
||||
Mode int //mode为0生产模式,1、为测试模式、2为开发模式
|
||||
}
|
||||
|
||||
type HotimeDBBuilder struct {
|
||||
HoTimeDB *HoTimeDB
|
||||
table string
|
||||
selects []interface{}
|
||||
join Slice
|
||||
where Map
|
||||
lastWhere Map
|
||||
page int
|
||||
pageRow int
|
||||
}
|
||||
|
||||
func (that *HoTimeDB) Table(table string) *HotimeDBBuilder {
|
||||
|
||||
return &HotimeDBBuilder{HoTimeDB: that, table: table, where: Map{}}
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) Get(qu ...interface{}) Map {
|
||||
|
||||
return that.HoTimeDB.Get(that.table, that.join, qu, that.where)
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) Count() int {
|
||||
|
||||
return that.HoTimeDB.Count(that.table, that.join, that.where)
|
||||
}
|
||||
func (that *HotimeDBBuilder) Page(page, pageRow int) *HotimeDBBuilder {
|
||||
that.page = page
|
||||
that.pageRow = pageRow
|
||||
return that
|
||||
}
|
||||
func (that *HotimeDBBuilder) Select(qu ...interface{}) []Map {
|
||||
if that.page != 0 {
|
||||
return that.HoTimeDB.Page(that.page, that.pageRow).PageSelect(that.table, that.join, qu, that.where)
|
||||
}
|
||||
return that.HoTimeDB.Select(that.table, that.join, qu, that.where)
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) Update(qu ...interface{}) int64 {
|
||||
lth := len(qu)
|
||||
if lth == 0 {
|
||||
return 0
|
||||
}
|
||||
data := Map{}
|
||||
if lth == 1 {
|
||||
data = ObjToMap(qu[0])
|
||||
}
|
||||
if lth > 1 {
|
||||
for k := 1; k < lth; k++ {
|
||||
data[ObjToStr(k-1)] = qu[k]
|
||||
k++
|
||||
}
|
||||
}
|
||||
|
||||
return that.HoTimeDB.Update(that.table, data, that.where)
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) Delete() int64 {
|
||||
|
||||
return that.HoTimeDB.Delete(that.table, that.where)
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) LeftJoin(table, joinStr string) *HotimeDBBuilder {
|
||||
that.Join(Map{"[>]" + table: joinStr})
|
||||
return that
|
||||
|
||||
}
|
||||
func (that *HotimeDBBuilder) RightJoin(table, joinStr string) *HotimeDBBuilder {
|
||||
that.Join(Map{"[<]" + table: joinStr})
|
||||
return that
|
||||
|
||||
}
|
||||
func (that *HotimeDBBuilder) InnerJoin(table, joinStr string) *HotimeDBBuilder {
|
||||
that.Join(Map{"[><]" + table: joinStr})
|
||||
return that
|
||||
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) FullJoin(table, joinStr string) *HotimeDBBuilder {
|
||||
that.Join(Map{"[<>]" + table: joinStr})
|
||||
return that
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) Join(qu ...interface{}) *HotimeDBBuilder {
|
||||
lth := len(qu)
|
||||
if lth == 0 {
|
||||
return that
|
||||
}
|
||||
data := Map{}
|
||||
if lth == 1 {
|
||||
data = ObjToMap(qu[0])
|
||||
}
|
||||
if lth > 1 {
|
||||
for k := 1; k < lth; k++ {
|
||||
data[ObjToStr(k-1)] = qu[k]
|
||||
k++
|
||||
}
|
||||
}
|
||||
|
||||
if that.join == nil {
|
||||
that.join = Slice{}
|
||||
}
|
||||
if data == nil {
|
||||
return that
|
||||
}
|
||||
|
||||
that.join = append(that.join, data)
|
||||
return that
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) And(qu ...interface{}) *HotimeDBBuilder {
|
||||
|
||||
lth := len(qu)
|
||||
if lth == 0 {
|
||||
return that
|
||||
}
|
||||
var where Map
|
||||
if lth == 1 {
|
||||
where = ObjToMap(qu[0])
|
||||
}
|
||||
if lth > 1 {
|
||||
where = Map{}
|
||||
for k := 1; k < lth; k++ {
|
||||
where[ObjToStr(k-1)] = qu[k]
|
||||
k++
|
||||
}
|
||||
}
|
||||
|
||||
if where == nil {
|
||||
return that
|
||||
}
|
||||
|
||||
if that.lastWhere != nil {
|
||||
that.lastWhere["AND"] = where
|
||||
that.lastWhere = where
|
||||
return that
|
||||
}
|
||||
that.lastWhere = where
|
||||
that.where = Map{"AND": where}
|
||||
|
||||
return that
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) Or(qu ...interface{}) *HotimeDBBuilder {
|
||||
lth := len(qu)
|
||||
if lth == 0 {
|
||||
return that
|
||||
}
|
||||
var where Map
|
||||
if lth == 1 {
|
||||
where = ObjToMap(qu[0])
|
||||
}
|
||||
if lth > 1 {
|
||||
where = Map{}
|
||||
for k := 1; k < lth; k++ {
|
||||
where[ObjToStr(k-1)] = qu[k]
|
||||
k++
|
||||
}
|
||||
}
|
||||
if where == nil {
|
||||
return that
|
||||
}
|
||||
|
||||
if that.lastWhere != nil {
|
||||
that.lastWhere["OR"] = where
|
||||
that.lastWhere = where
|
||||
return that
|
||||
}
|
||||
that.lastWhere = where
|
||||
that.where = Map{"Or": where}
|
||||
|
||||
return that
|
||||
}
|
||||
func (that *HotimeDBBuilder) Where(qu ...interface{}) *HotimeDBBuilder {
|
||||
|
||||
lth := len(qu)
|
||||
if lth == 0 {
|
||||
return that
|
||||
}
|
||||
var where Map
|
||||
if lth == 1 {
|
||||
where = ObjToMap(qu[0])
|
||||
}
|
||||
if lth > 1 {
|
||||
where = Map{}
|
||||
for k := 1; k < lth; k++ {
|
||||
where[ObjToStr(k-1)] = qu[k]
|
||||
k++
|
||||
}
|
||||
}
|
||||
|
||||
if where == nil {
|
||||
return that
|
||||
}
|
||||
|
||||
if that.lastWhere != nil {
|
||||
that.lastWhere["AND"] = where
|
||||
that.lastWhere = where
|
||||
return that
|
||||
}
|
||||
that.lastWhere = where
|
||||
that.where = Map{"AND": that.lastWhere}
|
||||
|
||||
return that
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) From(table string) *HotimeDBBuilder {
|
||||
that.table = table
|
||||
return that
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) Order(qu ...interface{}) *HotimeDBBuilder {
|
||||
that.where["ORDER"] = ObjToSlice(qu)
|
||||
return that
|
||||
}
|
||||
func (that *HotimeDBBuilder) Limit(qu ...interface{}) *HotimeDBBuilder {
|
||||
that.where["LIMIT"] = ObjToSlice(qu)
|
||||
return that
|
||||
}
|
||||
|
||||
func (that *HotimeDBBuilder) Group(qu ...interface{}) *HotimeDBBuilder {
|
||||
that.where["GROUP"] = ObjToSlice(qu)
|
||||
return that
|
||||
}
|
||||
|
||||
// SetConnect 设置数据库配置连接
|
||||
@@ -44,7 +271,11 @@ func (that *HoTimeDB) GetType() string {
|
||||
|
||||
// Action 事务,如果action返回true则执行成功;false则回滚
|
||||
func (that *HoTimeDB) Action(action func(db HoTimeDB) (isSuccess bool)) (isSuccess bool) {
|
||||
db := HoTimeDB{DB: that.DB, HoTimeCache: that.HoTimeCache, Prefix: that.Prefix}
|
||||
db := HoTimeDB{that.DB, that.ContextBase, that.DBName,
|
||||
that.HoTimeCache, that.Log, that.Type,
|
||||
that.Prefix, that.LastQuery, that.LastData,
|
||||
that.ConnectFunc, that.LastErr, that.limit, that.Tx,
|
||||
that.SlaveDB, that.Mode}
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
that.LastErr.SetError(err)
|
||||
@@ -87,7 +318,7 @@ func (that *HoTimeDB) InitDb(err ...*Error) *Error {
|
||||
e := that.SlaveDB.Ping()
|
||||
that.LastErr.SetError(e)
|
||||
}
|
||||
|
||||
//that.DB.SetConnMaxLifetime(time.Second)
|
||||
return that.LastErr
|
||||
}
|
||||
|
||||
@@ -260,7 +491,7 @@ func (that *HoTimeDB) backupCol(tt string) string {
|
||||
for k := range data[0] {
|
||||
|
||||
if tempLthData == lthCol-1 {
|
||||
str += "`" + k + "`)"
|
||||
str += "`" + k + "`) "
|
||||
} else {
|
||||
str += "`" + k + "`,"
|
||||
}
|
||||
@@ -284,7 +515,7 @@ func (that *HoTimeDB) backupCol(tt string) string {
|
||||
}
|
||||
|
||||
if m == lthCol-1 {
|
||||
str += v + ")"
|
||||
str += v + ") "
|
||||
|
||||
} else {
|
||||
str += v + ","
|
||||
@@ -306,7 +537,11 @@ func (that *HoTimeDB) md5(query string, args ...interface{}) string {
|
||||
}
|
||||
|
||||
func (that *HoTimeDB) Query(query string, args ...interface{}) []Map {
|
||||
|
||||
defer func() {
|
||||
if that.Mode != 0 {
|
||||
that.Log.Info("SQL:"+that.LastQuery, " DATA:", that.LastData, " ERROR:", that.LastErr.GetError())
|
||||
}
|
||||
}()
|
||||
//fmt.Println(query)
|
||||
var err error
|
||||
var resl *sql.Rows
|
||||
@@ -331,16 +566,18 @@ func (that *HoTimeDB) Query(query string, args ...interface{}) []Map {
|
||||
resl, err = db.Query(query, args...)
|
||||
}
|
||||
|
||||
if err != nil && that.LastErr.GetError() != nil &&
|
||||
that.LastErr.GetError().Error() == err.Error() {
|
||||
return nil
|
||||
}
|
||||
|
||||
that.LastErr.SetError(err)
|
||||
if err != nil {
|
||||
if err = db.Ping(); err != nil {
|
||||
that.LastErr.SetError(err)
|
||||
_ = that.InitDb()
|
||||
if that.LastErr.GetError() != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err = db.Ping(); err == nil {
|
||||
return that.Query(query, args...)
|
||||
}
|
||||
that.LastErr.SetError(err)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -348,7 +585,11 @@ func (that *HoTimeDB) Query(query string, args ...interface{}) []Map {
|
||||
}
|
||||
|
||||
func (that *HoTimeDB) Exec(query string, args ...interface{}) (sql.Result, *Error) {
|
||||
|
||||
defer func() {
|
||||
if that.Mode != 0 {
|
||||
that.Log.Info("SQL: "+that.LastQuery, " DATA: ", that.LastData, " ERROR: ", that.LastErr.GetError())
|
||||
}
|
||||
}()
|
||||
that.LastQuery = query
|
||||
that.LastData = args
|
||||
var e error
|
||||
@@ -366,19 +607,19 @@ func (that *HoTimeDB) Exec(query string, args ...interface{}) (sql.Result, *Erro
|
||||
resl, e = that.DB.Exec(query, args...)
|
||||
}
|
||||
|
||||
if e != nil && that.LastErr.GetError() != nil &&
|
||||
that.LastErr.GetError().Error() == e.Error() {
|
||||
return resl, that.LastErr
|
||||
}
|
||||
that.LastErr.SetError(e)
|
||||
|
||||
//判断是否连接断开了
|
||||
if e != nil {
|
||||
|
||||
if e = that.DB.Ping(); e != nil {
|
||||
that.LastErr.SetError(e)
|
||||
_ = that.InitDb()
|
||||
if that.LastErr.GetError() != nil {
|
||||
return resl, that.LastErr
|
||||
}
|
||||
if e = that.DB.Ping(); e == nil {
|
||||
return that.Exec(query, args...)
|
||||
}
|
||||
that.LastErr.SetError(e)
|
||||
return resl, that.LastErr
|
||||
}
|
||||
|
||||
return resl, that.LastErr
|
||||
@@ -421,17 +662,20 @@ func (that *HoTimeDB) Select(table string, qu ...interface{}) []Map {
|
||||
if reflect.ValueOf(qu[intQs]).Type().String() == "string" {
|
||||
query += " " + qu[intQs].(string)
|
||||
} else {
|
||||
for i := 0; i < len(qu[intQs].(Slice)); i++ {
|
||||
k := qu[intQs].(Slice)[i].(string)
|
||||
if strings.Contains(k, " AS ") {
|
||||
data := ObjToSlice(qu[intQs])
|
||||
for i := 0; i < len(data); i++ {
|
||||
k := data.GetString(i)
|
||||
if strings.Contains(k, " AS ") ||
|
||||
strings.Contains(k, ".") {
|
||||
|
||||
query += " " + k + " "
|
||||
|
||||
} else {
|
||||
|
||||
query += " `" + k + "` "
|
||||
}
|
||||
|
||||
if i+1 != len(qu[intQs].(Slice)) {
|
||||
if i+1 != len(data) {
|
||||
query = query + ", "
|
||||
}
|
||||
|
||||
@@ -442,33 +686,75 @@ func (that *HoTimeDB) Select(table string, qu ...interface{}) []Map {
|
||||
query += " *"
|
||||
}
|
||||
if !strings.Contains(table, ".") && !strings.Contains(table, " AS ") {
|
||||
query += " FROM `" + that.Prefix + table + "`"
|
||||
query += " FROM `" + that.Prefix + table + "` "
|
||||
} else {
|
||||
query += " FROM " + that.Prefix + table
|
||||
query += " FROM " + that.Prefix + table + " "
|
||||
}
|
||||
|
||||
if join {
|
||||
var testQu = []string{}
|
||||
testQuData := qu[0].(Map)
|
||||
for key, _ := range testQuData {
|
||||
//fmt.Println(key, ":", value)
|
||||
testQu = append(testQu, key)
|
||||
testQuData := Map{}
|
||||
if reflect.ValueOf(qu[0]).Type().String() == "common.Map" {
|
||||
testQuData = qu[0].(Map)
|
||||
for key, _ := range testQuData {
|
||||
//fmt.Println(key, ":", value)
|
||||
testQu = append(testQu, key)
|
||||
}
|
||||
}
|
||||
|
||||
if reflect.ValueOf(qu[0]).Type().String() == "common.Slice" {
|
||||
|
||||
for key, _ := range testQuData {
|
||||
v := testQuData.GetMap(key)
|
||||
for k1, v1 := range v {
|
||||
testQu = append(testQu, k1)
|
||||
testQuData[k1] = v1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sort.Strings(testQu)
|
||||
|
||||
for _, k := range testQu {
|
||||
v := testQuData[k]
|
||||
switch Substr(k, 0, 3) {
|
||||
case "[>]":
|
||||
query += " LEFT JOIN `" + Substr(k, 3, len(k)-3) + "` ON " + v.(string)
|
||||
func() {
|
||||
table := Substr(k, 3, len(k)-3)
|
||||
if !strings.Contains(table, " ") {
|
||||
table = "`" + table + "`"
|
||||
}
|
||||
query += " LEFT JOIN " + table + " ON " + v.(string) + " "
|
||||
}()
|
||||
case "[<]":
|
||||
query += " RIGHT JOIN `" + Substr(k, 3, len(k)-3) + "` ON " + v.(string)
|
||||
func() {
|
||||
table := Substr(k, 3, len(k)-3)
|
||||
if !strings.Contains(table, " ") {
|
||||
table = "`" + table + "`"
|
||||
}
|
||||
query += " RIGHT JOIN " + table + " ON " + v.(string) + " "
|
||||
}()
|
||||
|
||||
}
|
||||
switch Substr(k, 0, 4) {
|
||||
case "[<>]":
|
||||
query += " FULL JOIN `" + Substr(k, 4, len(k)-4) + "` ON " + v.(string)
|
||||
func() {
|
||||
table := Substr(k, 4, len(k)-4)
|
||||
if !strings.Contains(table, " ") {
|
||||
table = "`" + table + "`"
|
||||
}
|
||||
query += " FULL JOIN " + table + " ON " + v.(string) + " "
|
||||
}()
|
||||
|
||||
case "[><]":
|
||||
query += " INNER JOIN `" + Substr(k, 4, len(k)-4) + "` ON " + v.(string)
|
||||
func() {
|
||||
table := Substr(k, 4, len(k)-4)
|
||||
if !strings.Contains(table, " ") {
|
||||
table = "`" + table + "`"
|
||||
}
|
||||
query += " INNER JOIN " + table + " ON " + v.(string) + " "
|
||||
}()
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -479,7 +765,7 @@ func (that *HoTimeDB) Select(table string, qu ...interface{}) []Map {
|
||||
|
||||
temp, resWhere := that.where(where)
|
||||
|
||||
query += temp
|
||||
query += temp + ";"
|
||||
qs = append(qs, resWhere...)
|
||||
md5 := that.md5(query, qs...)
|
||||
|
||||
@@ -606,8 +892,7 @@ func (that *HoTimeDB) where(data Map) (string, []interface{}) {
|
||||
if v != nil && reflect.ValueOf(v).Type().String() == "common.Slice" && len(v.(Slice)) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if v != nil && reflect.ValueOf(v).Type().String() == "[]interface {}" && len(v.([]interface{})) == 0 {
|
||||
if v != nil && strings.Contains(reflect.ValueOf(v).Type().String(), "[]") && len(ObjToSlice(v)) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -620,7 +905,16 @@ func (that *HoTimeDB) where(data Map) (string, []interface{}) {
|
||||
}
|
||||
|
||||
if len(where) != 0 {
|
||||
where = " WHERE " + where
|
||||
hasWhere := true
|
||||
for _, v := range vcond {
|
||||
if strings.Index(where, v) == 0 {
|
||||
hasWhere = false
|
||||
}
|
||||
}
|
||||
|
||||
if hasWhere {
|
||||
where = " WHERE " + where + " "
|
||||
}
|
||||
}
|
||||
|
||||
//特殊字符
|
||||
@@ -636,31 +930,31 @@ func (that *HoTimeDB) where(data Map) (string, []interface{}) {
|
||||
v := data[k]
|
||||
if vcond[j] == k {
|
||||
if k == "ORDER" {
|
||||
where += " " + k + " BY "
|
||||
where += k + " BY "
|
||||
//fmt.Println(reflect.ValueOf(v).Type())
|
||||
|
||||
//break
|
||||
} else if k == "GROUP" {
|
||||
|
||||
where += " " + k + " BY "
|
||||
where += k + " BY "
|
||||
} else {
|
||||
|
||||
where += " " + k
|
||||
where += k
|
||||
}
|
||||
|
||||
if reflect.ValueOf(v).Type().String() == "common.Slice" {
|
||||
for i := 0; i < len(v.(Slice)); i++ {
|
||||
where += " " + ObjToStr(v.(Slice)[i])
|
||||
where += " " + ObjToStr(v.(Slice)[i]) + " "
|
||||
|
||||
if len(v.(Slice)) != i+1 {
|
||||
where += ","
|
||||
where += ", "
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
} else {
|
||||
//fmt.Println(v)
|
||||
where += " " + ObjToStr(v)
|
||||
where += " " + ObjToStr(v) + " "
|
||||
}
|
||||
|
||||
break
|
||||
@@ -688,45 +982,48 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
|
||||
case "[>]":
|
||||
k = strings.Replace(k, "[>]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + ">? "
|
||||
res = append(res, v)
|
||||
case "[<]":
|
||||
k = strings.Replace(k, "[<]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + "<? "
|
||||
res = append(res, v)
|
||||
case "[!]":
|
||||
k = strings.Replace(k, "[!]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where, res = that.notIn(k, v, where, res)
|
||||
case "[#]":
|
||||
k = strings.Replace(k, "[#]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += " " + k + "=" + ObjToStr(v)
|
||||
where += " " + k + "=" + ObjToStr(v) + " "
|
||||
case "[##]": //直接添加value到sql,需要考虑防注入,value比如:"a>b"
|
||||
|
||||
where += " " + ObjToStr(v)
|
||||
case "[#!]":
|
||||
k = strings.Replace(k, "[#!]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += " " + k + "!=" + ObjToStr(v)
|
||||
where += " " + k + "!=" + ObjToStr(v) + " "
|
||||
case "[!#]":
|
||||
k = strings.Replace(k, "[!#]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += " " + k + "!=" + ObjToStr(v)
|
||||
where += " " + k + "!=" + ObjToStr(v) + " "
|
||||
case "[~]":
|
||||
k = strings.Replace(k, "[~]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + " LIKE ? "
|
||||
v = "%" + ObjToStr(v) + "%"
|
||||
@@ -734,15 +1031,15 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
|
||||
case "[!~]": //左边任意
|
||||
k = strings.Replace(k, "[~]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + " LIKE ? "
|
||||
v = "%" + ObjToStr(v)
|
||||
v = "%" + ObjToStr(v) + ""
|
||||
res = append(res, v)
|
||||
case "[~!]": //右边任意
|
||||
k = strings.Replace(k, "[~]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + " LIKE ? "
|
||||
v = ObjToStr(v) + "%"
|
||||
@@ -750,7 +1047,7 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
|
||||
case "[~~]": //手动任意
|
||||
k = strings.Replace(k, "[~]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + " LIKE ? "
|
||||
//v = ObjToStr(v)
|
||||
@@ -764,21 +1061,21 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
|
||||
case "[>=]":
|
||||
k = strings.Replace(k, "[>=]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + ">=? "
|
||||
res = append(res, v)
|
||||
case "[<=]":
|
||||
k = strings.Replace(k, "[<=]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + "<=? "
|
||||
res = append(res, v)
|
||||
case "[><]":
|
||||
k = strings.Replace(k, "[><]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + " NOT BETWEEN ? AND ? "
|
||||
res = append(res, v.(Slice)[0])
|
||||
@@ -786,29 +1083,31 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
|
||||
case "[<>]":
|
||||
k = strings.Replace(k, "[<>]", "", -1)
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
where += k + " BETWEEN ? AND ? "
|
||||
res = append(res, v.(Slice)[0])
|
||||
res = append(res, v.(Slice)[1])
|
||||
default:
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
if reflect.ValueOf(v).Type().String() == "common.Slice" {
|
||||
if reflect.ValueOf(v).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(v).Type().String(), "[]") {
|
||||
vs := ObjToSlice(v)
|
||||
if len(vs) == 0 {
|
||||
return where, res
|
||||
}
|
||||
|
||||
where += k + " IN ("
|
||||
res = append(res, v.(Slice)...)
|
||||
if len(v.(Slice)) == 0 {
|
||||
where += ") "
|
||||
} else {
|
||||
for i := 0; i < len(v.(Slice)); i++ {
|
||||
if i+1 != len(v.(Slice)) {
|
||||
where += "?,"
|
||||
} else {
|
||||
where += "?) "
|
||||
}
|
||||
//res=append(res,(v.(Slice))[i])
|
||||
res = append(res, vs...)
|
||||
|
||||
for i := 0; i < len(vs); i++ {
|
||||
if i+1 != len(vs) {
|
||||
where += "?,"
|
||||
} else {
|
||||
where += "?) "
|
||||
}
|
||||
//res=append(res,(v.(Slice))[i])
|
||||
}
|
||||
|
||||
} else {
|
||||
@@ -822,35 +1121,28 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) {
|
||||
} else {
|
||||
//fmt.Println(reflect.ValueOf(v).Type().String())
|
||||
if !strings.Contains(k, ".") {
|
||||
k = "`" + k + "`"
|
||||
k = "`" + k + "` "
|
||||
}
|
||||
if v == nil {
|
||||
where += k + " IS NULL"
|
||||
} else if reflect.ValueOf(v).Type().String() == "common.Slice" {
|
||||
|
||||
where += k + " IS NULL "
|
||||
} else if reflect.ValueOf(v).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(v).Type().String(), "[]") {
|
||||
vs := ObjToSlice(v)
|
||||
//fmt.Println(v)
|
||||
where += k + " IN ("
|
||||
res = append(res, v.(Slice)...)
|
||||
for i := 0; i < len(v.(Slice)); i++ {
|
||||
if i+1 != len(v.(Slice)) {
|
||||
where += "?,"
|
||||
} else {
|
||||
where += "?) "
|
||||
}
|
||||
//res=append(res,(v.(Slice))[i])
|
||||
if len(vs) == 0 {
|
||||
return where, res
|
||||
}
|
||||
} else if reflect.ValueOf(v).Type().String() == "[]interface {}" {
|
||||
where += k + " IN ("
|
||||
res = append(res, vs...)
|
||||
|
||||
where += k + " IN ("
|
||||
res = append(res, v.([]interface{})...)
|
||||
for i := 0; i < len(v.([]interface{})); i++ {
|
||||
if i+1 != len(v.([]interface{})) {
|
||||
for i := 0; i < len(vs); i++ {
|
||||
if i+1 != len(vs) {
|
||||
where += "?,"
|
||||
} else {
|
||||
where += "?) "
|
||||
}
|
||||
//res=append(res,(v.(Slice))[i])
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
where += k + "=? "
|
||||
@@ -870,28 +1162,23 @@ func (that *HoTimeDB) notIn(k string, v interface{}, where string, res []interfa
|
||||
|
||||
where += k + " IS NOT NULL "
|
||||
|
||||
} else if reflect.ValueOf(v).Type().String() == "common.Slice" {
|
||||
} else if reflect.ValueOf(v).Type().String() == "common.Slice" || strings.Contains(reflect.ValueOf(v).Type().String(), "[]") {
|
||||
vs := ObjToSlice(v)
|
||||
if len(vs) == 0 {
|
||||
return where, res
|
||||
}
|
||||
where += k + " NOT IN ("
|
||||
res = append(res, v.(Slice)...)
|
||||
for i := 0; i < len(v.(Slice)); i++ {
|
||||
if i+1 != len(v.(Slice)) {
|
||||
where += "?,"
|
||||
} else {
|
||||
where += "?) "
|
||||
}
|
||||
//res=append(res,(v.(Slice))[i])
|
||||
}
|
||||
} else if reflect.ValueOf(v).Type().String() == "[]interface {}" {
|
||||
where += k + " NOT IN ("
|
||||
res = append(res, v.([]interface{})...)
|
||||
for i := 0; i < len(v.([]interface{})); i++ {
|
||||
if i+1 != len(v.([]interface{})) {
|
||||
res = append(res, vs...)
|
||||
|
||||
for i := 0; i < len(vs); i++ {
|
||||
if i+1 != len(vs) {
|
||||
where += "?,"
|
||||
} else {
|
||||
where += "?) "
|
||||
}
|
||||
//res=append(res,(v.(Slice))[i])
|
||||
}
|
||||
|
||||
} else {
|
||||
|
||||
where += k + " !=? "
|
||||
@@ -938,7 +1225,10 @@ func (that *HoTimeDB) cond(tag string, data Map) (string, []interface{}) {
|
||||
if x == len(condition) {
|
||||
|
||||
tv, vv := that.varCond(k, v)
|
||||
|
||||
if tv == "" {
|
||||
lens--
|
||||
continue
|
||||
}
|
||||
res = append(res, vv...)
|
||||
if lens--; lens <= 0 {
|
||||
where += tv + ""
|
||||
@@ -969,7 +1259,7 @@ func (that *HoTimeDB) Update(table string, data Map, where Map) int64 {
|
||||
} else {
|
||||
qs = append(qs, v)
|
||||
}
|
||||
query += "`" + k + "`=" + vstr + ""
|
||||
query += "`" + k + "`=" + vstr + " "
|
||||
if tp--; tp != 0 {
|
||||
query += ", "
|
||||
}
|
||||
@@ -978,7 +1268,7 @@ func (that *HoTimeDB) Update(table string, data Map, where Map) int64 {
|
||||
temp, resWhere := that.where(where)
|
||||
//fmt.Println(resWhere)
|
||||
|
||||
query += temp
|
||||
query += temp + ";"
|
||||
qs = append(qs, resWhere...)
|
||||
|
||||
res, err := that.Exec(query, qs...)
|
||||
@@ -1003,7 +1293,7 @@ func (that *HoTimeDB) Delete(table string, data map[string]interface{}) int64 {
|
||||
query := "DELETE FROM " + that.Prefix + table + " "
|
||||
|
||||
temp, resWhere := that.where(data)
|
||||
query += temp
|
||||
query += temp + ";"
|
||||
|
||||
res, err := that.Exec(query, resWhere...)
|
||||
rows := int64(0)
|
||||
|
||||
@@ -1,118 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"code.hoteas.com/golang/hotime/common"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
//高级加密标准(Adevanced Encryption Standard ,AES)
|
||||
|
||||
//16,24,32位字符串的话,分别对应AES-128,AES-192,AES-256 加密方法
|
||||
//key不能泄露
|
||||
var PwdKey = []byte("mif022h3g9geAHUHY432,:da1adag389")
|
||||
|
||||
//PKCS7 填充模式
|
||||
func pKCS7Padding(ciphertext []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(ciphertext)%blockSize
|
||||
//Repeat()函数的功能是把切片[]byte{byte(padding)}复制padding个,然后合并成新的字节切片返回
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(ciphertext, padtext...)
|
||||
}
|
||||
|
||||
//填充的反向操作,删除填充字符串
|
||||
func pKCS7UnPadding(origData []byte) ([]byte, error) {
|
||||
//获取数据长度
|
||||
length := len(origData)
|
||||
if length == 0 {
|
||||
return nil, errors.New("加密字符串错误!")
|
||||
} else {
|
||||
//获取填充字符串长度
|
||||
unpadding := int(origData[length-1])
|
||||
//截取切片,删除填充字节,并且返回明文
|
||||
return origData[:(length - unpadding)], nil
|
||||
}
|
||||
}
|
||||
|
||||
//实现加密
|
||||
func AesEcrypt(origData []byte, key []byte) ([]byte, error) {
|
||||
//创建加密算法实例
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
//获取块的大小
|
||||
blockSize := block.BlockSize()
|
||||
//对数据进行填充,让数据长度满足需求
|
||||
origData = pKCS7Padding(origData, blockSize)
|
||||
//采用AES加密方法中CBC加密模式
|
||||
blocMode := cipher.NewCBCEncrypter(block, key[:blockSize])
|
||||
crypted := make([]byte, len(origData))
|
||||
//执行加密
|
||||
blocMode.CryptBlocks(crypted, origData)
|
||||
return crypted, nil
|
||||
}
|
||||
|
||||
//实现解密
|
||||
func AesDeCrypt(cypted []byte, key []byte) (bytes []byte, err error) {
|
||||
//异常处理
|
||||
defer func() {
|
||||
if e := recover(); e != nil {
|
||||
//that.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
|
||||
fmt.Println(err)
|
||||
err = errors.New(common.ObjToStr(e))
|
||||
}
|
||||
}()
|
||||
//创建加密算法实例
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
//获取块大小
|
||||
blockSize := block.BlockSize()
|
||||
//创建加密客户端实例
|
||||
blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
|
||||
origData := make([]byte, len(cypted))
|
||||
//这个函数也可以用来解密
|
||||
blockMode.CryptBlocks(origData, cypted)
|
||||
//去除填充字符串
|
||||
origData, err = pKCS7UnPadding(origData)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return origData, err
|
||||
}
|
||||
|
||||
//加密base64
|
||||
func EnPwdCode(pwd []byte) (string, error) {
|
||||
result, err := AesEcrypt(pwd, PwdKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(result), err
|
||||
}
|
||||
|
||||
//解密
|
||||
func DePwdCode(pwd string) ([]byte, error) {
|
||||
//解密base64字符串
|
||||
pwdByte, err := base64.StdEncoding.DecodeString(pwd)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return nil, err
|
||||
}
|
||||
//执行AES解密
|
||||
return AesDeCrypt(pwdByte, PwdKey)
|
||||
|
||||
}
|
||||
|
||||
//func main() {
|
||||
// str := []byte("12fff我是ww.topgoer.com的站长枯藤")
|
||||
// pwd, _ := EnPwdCode(str)
|
||||
// bytes, _ := DePwdCode(pwd)
|
||||
// fmt.Println(string(bytes))
|
||||
//}
|
||||
+70
-76
@@ -3,108 +3,102 @@ package app
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ArticleCtr = Ctr{
|
||||
"info": func(that *Context) {
|
||||
sn := that.Req.FormValue("sn")
|
||||
article := that.Db.Get("article", Map{"[><]ctg_article": "article.id=ctg_article.article_id"}, "article.*,ctg_article.ctg_id AS sctg_id", Map{"ctg_article.sn": sn})
|
||||
if article == nil {
|
||||
that.Display(4, "找不到对应数据")
|
||||
return
|
||||
}
|
||||
ctgId := article.GetCeilInt64("sctg_id")
|
||||
ctg := that.Db.Get("ctg", "*", Map{"id": ctgId})
|
||||
parents := []Map{}
|
||||
parentId := ctg.GetCeilInt64("parent_id")
|
||||
article["tongji"] = that.Db.Select("ctg", "sn,name,img,parent_id", Map{"parent_id": parentId})
|
||||
for true {
|
||||
|
||||
"getdispatchs": func(that *Context) {
|
||||
if parentId == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
parent := that.Db.Get("ctg", "sn,name,img,parent_id", Map{"id": parentId})
|
||||
if parent == nil {
|
||||
break
|
||||
}
|
||||
|
||||
parents = append(parents, parent)
|
||||
parentId = parent.GetCeilInt64("parent_id")
|
||||
|
||||
//判断类型
|
||||
tp := that.Req.FormValue("type")
|
||||
//判断类型
|
||||
data := Map{"del_flag": 0}
|
||||
if tp == "notify" {
|
||||
data["notify_id[!]"] = nil
|
||||
}
|
||||
|
||||
if tp == "policy" {
|
||||
data["policy_id[!]"] = nil
|
||||
}
|
||||
|
||||
if tp == "declare" {
|
||||
data["declare_id[!]"] = nil
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "GROUP": "dispatch_name"}
|
||||
} else {
|
||||
data["GROUP"] = "dispatch_name"
|
||||
}
|
||||
|
||||
res := that.Db.Select("article", "dispatch_name", data)
|
||||
that.Display(0, res)
|
||||
ctg["parents"] = parents
|
||||
|
||||
article["ctg"] = ctg
|
||||
that.Display(0, article)
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
|
||||
"list": func(that *Context) {
|
||||
sn := that.Req.FormValue("ctg_sn") //ctgsn
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
if page == 0 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
if pageSize == 0 {
|
||||
pageSize = 10
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
|
||||
lunbo := ObjToInt(that.Req.FormValue("lunbo"))
|
||||
|
||||
sort := that.Req.FormValue("sort")
|
||||
|
||||
where := Map{"article.push_time[<]": time.Now().Format("2006-01-02 15:04"), "article.state": 0}
|
||||
if sn != "" {
|
||||
ctg := that.Db.Get("ctg", "id", Map{"sn": sn})
|
||||
if ctg != nil {
|
||||
where["ctg_article.ctg_id"] = ctg.GetCeilInt("id")
|
||||
}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("start_time") //ctgsn
|
||||
finishTime := that.Req.FormValue("finish_time") //ctgsn
|
||||
|
||||
if lunbo != 0 {
|
||||
where["article.lunbo"] = lunbo
|
||||
}
|
||||
|
||||
if len(startTime) > 5 {
|
||||
where["article.push_time[>=]"] = startTime
|
||||
}
|
||||
if len(finishTime) > 5 {
|
||||
where["article.push_time[<=]"] = finishTime
|
||||
}
|
||||
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
|
||||
where["OR"] = Map{"article.title[~]": keywords, "article.description[~]": keywords, "article.author[~]": keywords, "article.sn[~]": keywords, "article.origin[~]": keywords, "article.url[~]": keywords}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["release_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["release_time[<=]"] = finishTime
|
||||
if len(where) > 1 {
|
||||
where = Map{"AND": where}
|
||||
}
|
||||
|
||||
dispatchName := that.Req.FormValue("dispatch_name")
|
||||
if dispatchName != "" {
|
||||
data["dispatch_name"] = dispatchName
|
||||
if sort == "" {
|
||||
where["ORDER"] = Slice{"article.sort DESC", "article.push_time DESC"}
|
||||
}
|
||||
|
||||
//判断类型
|
||||
tp := that.Req.FormValue("type")
|
||||
if tp == "notify" {
|
||||
data["notify_id[!]"] = nil
|
||||
if sort == "time" {
|
||||
where["ORDER"] = "article.push_time DESC"
|
||||
}
|
||||
count := that.Db.Count("article", Map{"[><]ctg_article": "article.id=ctg_article.article_id"}, where)
|
||||
article := that.Db.Page(page, pageSize).PageSelect("article", Map{"[><]ctg_article": "article.id=ctg_article.article_id"}, "ctg_article.sn,article.img,article.title,article.description,article.push_time,article.lunbo,article.author,article.origin,article.url", where)
|
||||
|
||||
if tp == "policy" {
|
||||
data["policy_id[!]"] = nil
|
||||
}
|
||||
that.Display(0, Map{"count": count, "data": article})
|
||||
|
||||
if tp == "declare" {
|
||||
data["declare_id[!]"] = nil
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "ORDER": "release_time DESC"}
|
||||
}
|
||||
|
||||
count := that.Db.Count("article", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
|
||||
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status,policy_id,declare_id,notify_id,dispatch_name,policy_level", data)
|
||||
for _, v := range res {
|
||||
|
||||
if v.GetCeilInt("notify_id") > 0 {
|
||||
v["notify"] = that.Db.Get("notify", "tag", Map{"id": v.GetCeilInt("notify_id")})
|
||||
}
|
||||
if v.GetCeilInt("policy_id") > 0 {
|
||||
v["policy"] = that.Db.Get("policy", "tag", Map{"id": v.GetCeilInt("policy_id")})
|
||||
}
|
||||
if v.GetCeilInt("declare_id") > 0 {
|
||||
v["declare"] = that.Db.Get("declare", "money_scope_min,money_scope_max,status", Map{"id": v.GetCeilInt("declare_id")})
|
||||
}
|
||||
}
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,259 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"code.hoteas.com/golang/hotime/dri/aliyun"
|
||||
"code.hoteas.com/golang/hotime/dri/tencent"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var CompanyCtr = Ctr{
|
||||
|
||||
"search": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords == "" {
|
||||
keywords = that.Req.FormValue("company_name")
|
||||
}
|
||||
if keywords == "" {
|
||||
keywords = that.Req.FormValue("name")
|
||||
}
|
||||
|
||||
if len(keywords) < 2 {
|
||||
that.Display(0, Slice{})
|
||||
return
|
||||
}
|
||||
|
||||
res, err := aliyun.Company.GetCompanyList(keywords)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
that.Display(0, Slice{})
|
||||
return
|
||||
}
|
||||
if res.GetCeilInt64("status") != 200 {
|
||||
fmt.Println(err)
|
||||
that.Display(0, Slice{})
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, res.GetMap("data").GetSlice("list"))
|
||||
},
|
||||
"search_info": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
name := that.Req.FormValue("name")
|
||||
|
||||
if len(name) < 2 {
|
||||
that.Display(3, "找不到企业")
|
||||
return
|
||||
}
|
||||
|
||||
res, err := aliyun.Company.GetCompanyBaseInfo(name)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
that.Display(4, "查询失败")
|
||||
return
|
||||
}
|
||||
if res.GetBool("status") != true {
|
||||
fmt.Println(err)
|
||||
that.Display(4, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, res.GetMap("data"))
|
||||
},
|
||||
"info": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").Data})
|
||||
if user == nil {
|
||||
that.Display(4, "找不到用户")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("company", "*", Map{"id": user.GetCeilInt("company_id")})
|
||||
if res == nil {
|
||||
that.Display(4, "找不到企业")
|
||||
return
|
||||
}
|
||||
//先不做限制
|
||||
//if res.GetCeilInt("salesman_id")!=that.Session("salesman_id").ToCeilInt(){
|
||||
// that.Display(4,"不是你的企业")
|
||||
// return
|
||||
//}
|
||||
|
||||
//res["technology_center_flag"] = ObjToSlice(res["technology_center_flag"])
|
||||
//res["engineering_center_flag"] = ObjToSlice(res["engineering_center_flag"])
|
||||
//res["engineering_laboratory_flag"] = ObjToSlice(res["engineering_laboratory_flag"])
|
||||
//res["key_laboratory_flag"] = ObjToSlice(res["key_laboratory_flag"])
|
||||
//res["industrial_design_center_flag"] = ObjToSlice(res["industrial_design_center_flag"])
|
||||
//
|
||||
//res["high_level_talents_flag1"] = ObjToSlice(res["high_level_talents_flag1"])
|
||||
//
|
||||
//res["tags"] = ObjToSlice(res["tags"])
|
||||
|
||||
res["technology_center_flag"] = strToArray(res.GetString("technology_center_flag"))
|
||||
res["engineering_center_flag"] = strToArray(res.GetString("engineering_center_flag"))
|
||||
res["engineering_laboratory_flag"] = strToArray(res.GetString("engineering_laboratory_flag"))
|
||||
res["key_laboratory_flag"] = strToArray(res.GetString("key_laboratory_flag"))
|
||||
res["industrial_design_center_flag"] = strToArray(res.GetString("industrial_design_center_flag"))
|
||||
res["high_level_talents_flag1"] = strToArray(res.GetString("high_level_talents_flag1"))
|
||||
res["tags"] = strToArray(res.GetString("tags"))
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
"edit": func(that *Context) {
|
||||
|
||||
//if that.Session("user_id").Data == nil {
|
||||
// that.Display(2, "没有登录")
|
||||
// return
|
||||
//}
|
||||
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
//统一社会信用代码
|
||||
social_code := that.Req.FormValue("social_code")
|
||||
if social_code == "" {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
//企业名称
|
||||
company_name := that.Req.FormValue("company_name")
|
||||
if company_name == "" {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
//手机号
|
||||
phone := that.Req.FormValue("phone")
|
||||
if phone == "" {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
//姓名
|
||||
name := that.Req.FormValue("user_name")
|
||||
if name == "" {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
//验证码
|
||||
err := auth(that, phone, company_name, name)
|
||||
if err != nil {
|
||||
that.Display(3, err.Error())
|
||||
return
|
||||
}
|
||||
//营业执照路径
|
||||
business_license := that.Req.FormValue("business_license")
|
||||
if business_license == "" {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
user_id := that.Session("user_id").Data
|
||||
user := that.Db.Get("user", "*", Map{"id": user_id})
|
||||
if user == nil {
|
||||
that.Display(1, "没有找到该用户")
|
||||
return
|
||||
}
|
||||
company := that.Db.Get("company", "*", Map{"AND": Map{"id": id, "user_id": user_id}})
|
||||
if company == nil {
|
||||
that.Display(4, "不是属于你的企业")
|
||||
return
|
||||
}
|
||||
//认证
|
||||
authentication_flag := 1
|
||||
//if user.GetCeilInt("authentication_flag") == 0 {
|
||||
// authentication_flag = 1
|
||||
//}
|
||||
//通过base64图片获取信息
|
||||
|
||||
that.Db.Update("user", Map{"name": name, "phone": phone, "authentication_flag": authentication_flag}, Map{"id": user_id})
|
||||
|
||||
that.Db.Update("company", Map{"social_code": social_code, "name": company_name, "phone": phone, "business_license": business_license, "modify_time[#]": "now()"}, Map{"id": id})
|
||||
|
||||
//赠送一张券
|
||||
data := Map{
|
||||
"user_id": user_id,
|
||||
"coupon_id": 1,
|
||||
"code_no": "SN" + time.Now().Format("20060102150405") + getSn(),
|
||||
"effective_start_time[#]": "NOW()",
|
||||
"effective_end_time": time.Now().AddDate(0, 6, 0).Format("2006-01-02 15:04:05"),
|
||||
"source_type": 2,
|
||||
"status": 0,
|
||||
"admin_id": user.GetCeilInt("admin_id"),
|
||||
"create_time[#]": "NOW()",
|
||||
}
|
||||
//先判断是否领取过 source_type=2 是通过认证赠送的券
|
||||
couponCount := that.Db.Count("coupon_user", Map{"AND": Map{"user_id": user_id, "source_type": 2}})
|
||||
if couponCount == 0 {
|
||||
that.Db.Insert("coupon_user", data)
|
||||
}
|
||||
that.Display(0, "认证成功")
|
||||
},
|
||||
//上传营业执照
|
||||
"upload": func(this *Context) {
|
||||
file := this.Req.FormValue("file")
|
||||
|
||||
if len(file) < 100 {
|
||||
this.Display(3, "图片上传错误")
|
||||
return
|
||||
}
|
||||
|
||||
//fmt.Println(uimg)
|
||||
btes, e := base64.StdEncoding.DecodeString(file[strings.Index(file, ",")+1:]) //成图片文件并把文件写入到buffer
|
||||
//btes, e := base64.StdEncoding.DecodeString(file) //成图片文件并把文件写入到buffer
|
||||
if e != nil {
|
||||
this.Display(3, "无法解析图片")
|
||||
return
|
||||
}
|
||||
|
||||
//uimgPath:=time.Now().Format(this.Config.GetString("uimgPath"))
|
||||
path := time.Now().Format(this.Config.GetString("wxFilePath"))
|
||||
os.MkdirAll(this.Config.GetString("tpt")+"/"+path, os.ModeDir)
|
||||
filePath := path + Md5(ObjToStr(time.Now().Unix())) + ".jpg"
|
||||
|
||||
err2 := ioutil.WriteFile(this.Config.GetString("tpt")+"/"+filePath, btes, 0666) //buffer输出到jpg文件中(不做处理,直接写到文件)
|
||||
if err2 != nil {
|
||||
this.Display(3, "图片保存失败")
|
||||
return
|
||||
}
|
||||
tp := this.Req.FormValue("type")
|
||||
|
||||
if tp == "company" {
|
||||
data := tencent.Tencent.OCRCOMPANY(file)
|
||||
c := ObjToMap(data)
|
||||
if c != nil {
|
||||
c = c.GetMap("Response")
|
||||
c["url"] = filePath
|
||||
|
||||
} else {
|
||||
c = Map{"url": filePath}
|
||||
}
|
||||
this.Display(0, c)
|
||||
return
|
||||
}
|
||||
},
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var CouponCtr = Ctr{
|
||||
|
||||
"search": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
user_id := that.Session("user_id").Data
|
||||
user := that.Db.Get("user", "*", Map{"id": user_id})
|
||||
if user == nil {
|
||||
that.Display(1, "没有找到该用户")
|
||||
return
|
||||
}
|
||||
|
||||
//0-待使用,1-已使用,2-已过期
|
||||
|
||||
status := ObjToInt(that.Req.FormValue("status"))
|
||||
var data = Map{
|
||||
"coupon_user.user_id": user_id,
|
||||
"coupon_user.state": 0,
|
||||
}
|
||||
if that.Req.FormValue("status") != "" {
|
||||
data.Put("coupon_user.status", status)
|
||||
}
|
||||
|
||||
specMap := Map{"AND": data}
|
||||
if status == 0 {
|
||||
specMap.Put("ORDER", "coupon_user.status ASC,coupon_user.effective_end_time ASC,coupon_user.create_time DESC")
|
||||
}
|
||||
if status == 1 {
|
||||
specMap.Put("ORDER", "coupon_user.use_time DESC")
|
||||
}
|
||||
if status == 2 {
|
||||
specMap.Put("ORDER", "coupon_user.effective_end_time DESC")
|
||||
}
|
||||
|
||||
count := that.Db.Count("coupon_user", Map{"AND": data})
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("coupon_user",
|
||||
Map{"[>]coupon": "coupon_user.coupon_id = coupon.id"},
|
||||
"coupon_user.code_no,coupon_user.effective_start_time,coupon_user.effective_end_time,coupon_user.status,"+
|
||||
"coupon.coupon_amount,coupon.coupon_type,coupon.name,"+
|
||||
"coupon.description",
|
||||
specMap,
|
||||
)
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var CtgCtr = Ctr{
|
||||
"info": func(that *Context) {
|
||||
sn := that.Req.FormValue("sn")
|
||||
ctg := that.Db.Get("ctg", "*", Map{"sn": sn})
|
||||
parents := []Map{}
|
||||
parentId := ctg.GetCeilInt64("parent_id")
|
||||
ctg["tongji"] = that.Db.Select("ctg", "sn,name,img,parent_id", Map{"parent_id": parentId})
|
||||
for true {
|
||||
|
||||
if parentId == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
parent := that.Db.Get("ctg", "sn,name,img,parent_id", Map{"id": parentId})
|
||||
if parent == nil {
|
||||
break
|
||||
}
|
||||
|
||||
parents = append(parents, parent)
|
||||
parentId = parent.GetCeilInt64("parent_id")
|
||||
|
||||
}
|
||||
|
||||
if ctg.GetCeilInt64("article_id") != 0 {
|
||||
ctg["article"] = that.Db.Get("article", "*", Map{"id": ctg.GetCeilInt64("article_id")})
|
||||
}
|
||||
|
||||
ctg["parents"] = parents
|
||||
that.Display(0, ctg)
|
||||
},
|
||||
"list": func(that *Context) {
|
||||
sn := that.Req.FormValue("sn") //ctgsn
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page == 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize == 0 {
|
||||
pageSize = 50
|
||||
}
|
||||
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
|
||||
//sort:=that.Req.FormValue("sort")
|
||||
|
||||
where := Map{"state": 0}
|
||||
if sn != "" {
|
||||
ctg := that.Db.Get("ctg", "id", Map{"sn": sn})
|
||||
if ctg != nil {
|
||||
where["parent_id"] = ctg.GetCeilInt("id")
|
||||
}
|
||||
}
|
||||
|
||||
if keywords != "" {
|
||||
where["OR"] = Map{"name[~]": keywords, "url[~]": keywords, "sn[~]": keywords}
|
||||
}
|
||||
|
||||
if len(where) > 1 {
|
||||
where = Map{"AND": where}
|
||||
}
|
||||
|
||||
where["ORDER"] = Slice{"sort DESC", "id DESC"}
|
||||
|
||||
article := that.Db.Page(page, pageSize).PageSelect("ctg", "name,sn,sort,url,img", where)
|
||||
|
||||
that.Display(0, article)
|
||||
|
||||
},
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,241 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var FavoriteCtr = Ctr{
|
||||
//关注
|
||||
"follow": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
policyId := ObjToInt(that.Req.FormValue("policy_id"))
|
||||
notifyId := ObjToInt(that.Req.FormValue("notify_id"))
|
||||
declareId := ObjToInt(that.Req.FormValue("declare_id"))
|
||||
providerId := ObjToInt(that.Req.FormValue("provider_id"))
|
||||
|
||||
favorite := Map{}
|
||||
data := Map{}
|
||||
if providerId != 0 {
|
||||
data = Map{"provider_id": providerId, "user_id": that.Session("user_id").Data}
|
||||
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
|
||||
data["modify_time[#]"] = "now()"
|
||||
data["del_flag"] = 0
|
||||
data["type"] = 1
|
||||
|
||||
} else if notifyId != 0 {
|
||||
article := that.Db.Get("article", "id", Map{"notify_id": notifyId})
|
||||
if article != nil {
|
||||
data = Map{"notify_id": notifyId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
|
||||
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
|
||||
data["modify_time[#]"] = "now()"
|
||||
data["del_flag"] = 0
|
||||
data["type"] = 2
|
||||
}
|
||||
|
||||
} else if policyId != 0 {
|
||||
article := that.Db.Get("article", "id", Map{"policy_id": policyId})
|
||||
if article != nil {
|
||||
data = Map{"policy_id": policyId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
|
||||
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
|
||||
data["modify_time[#]"] = "now()"
|
||||
data["del_flag"] = 0
|
||||
data["type"] = 3
|
||||
}
|
||||
|
||||
} else if declareId != 0 {
|
||||
article := that.Db.Get("article", "id", Map{"declare_id": declareId})
|
||||
if article != nil {
|
||||
data = Map{"declare_id": declareId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
|
||||
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
|
||||
data["modify_time[#]"] = "now()"
|
||||
data["del_flag"] = 0
|
||||
data["type"] = 4
|
||||
}
|
||||
}
|
||||
|
||||
if len(data) != 0 {
|
||||
isFavorite := int64(0)
|
||||
if favorite != nil {
|
||||
isFavorite = that.Db.Update("favorite", data, Map{"id": favorite.GetCeilInt("id")})
|
||||
} else {
|
||||
data["create_time[#]"] = "now()"
|
||||
isFavorite = that.Db.Insert("favorite", data)
|
||||
}
|
||||
|
||||
if isFavorite != 0 {
|
||||
if data.GetCeilInt("article_id") != 0 {
|
||||
that.Db.Update("article", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("article_id")})
|
||||
}
|
||||
if data.GetCeilInt("notify_id") != 0 {
|
||||
that.Db.Update("notify", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("notify_id")})
|
||||
}
|
||||
if data.GetCeilInt("policy_id") != 0 {
|
||||
that.Db.Update("policy", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("policy_id")})
|
||||
}
|
||||
|
||||
if data.GetCeilInt("declare_id") != 0 {
|
||||
that.Db.Update("declare", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("declare_id")})
|
||||
}
|
||||
|
||||
if data.GetCeilInt("provider_id") != 0 {
|
||||
that.Db.Update("provider", Map{"favorite_num[#]": "favorite_num+1"}, Map{"id": data.GetCeilInt("provider_id")})
|
||||
}
|
||||
}
|
||||
|
||||
that.Display(0, "关注成功")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(4, "找不到关注对象")
|
||||
return
|
||||
|
||||
},
|
||||
|
||||
//关注
|
||||
"unfollow": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
policyId := ObjToInt(that.Req.FormValue("policy_id"))
|
||||
notifyId := ObjToInt(that.Req.FormValue("notify_id"))
|
||||
declareId := ObjToInt(that.Req.FormValue("declare_id"))
|
||||
providerId := ObjToInt(that.Req.FormValue("provider_id"))
|
||||
|
||||
favorite := Map{}
|
||||
data := Map{}
|
||||
if providerId != 0 {
|
||||
data = Map{"provider_id": providerId, "user_id": that.Session("user_id").Data}
|
||||
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
|
||||
data["modify_time[#]"] = "now()"
|
||||
data["del_flag"] = 1
|
||||
data["type"] = 1
|
||||
|
||||
} else if notifyId != 0 {
|
||||
article := that.Db.Get("article", "id", Map{"notify_id": notifyId})
|
||||
if article != nil {
|
||||
data = Map{"notify_id": notifyId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
|
||||
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
|
||||
data["modify_time[#]"] = "now()"
|
||||
data["del_flag"] = 1
|
||||
data["type"] = 2
|
||||
}
|
||||
} else if policyId != 0 {
|
||||
|
||||
article := that.Db.Get("article", "id", Map{"policy_id": policyId})
|
||||
if article != nil {
|
||||
data = Map{"policy_id": policyId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
|
||||
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
|
||||
data["modify_time[#]"] = "now()"
|
||||
data["del_flag"] = 1
|
||||
data["type"] = 3
|
||||
}
|
||||
|
||||
} else if declareId != 0 {
|
||||
article := that.Db.Get("article", "id", Map{"declare_id": declareId})
|
||||
if article != nil {
|
||||
data = Map{"declare_id": declareId, "article_id": article.GetCeilInt("id"), "user_id": that.Session("user_id").Data}
|
||||
favorite = that.Db.Get("favorite", "*", Map{"AND": data})
|
||||
data["modify_time[#]"] = "now()"
|
||||
data["del_flag"] = 1
|
||||
data["type"] = 4
|
||||
}
|
||||
}
|
||||
|
||||
if len(data) != 0 && favorite != nil {
|
||||
|
||||
isFavorite := that.Db.Update("favorite", data, Map{"id": favorite.GetCeilInt("id")})
|
||||
|
||||
if isFavorite != 0 {
|
||||
if data.GetCeilInt("article_id") != 0 {
|
||||
that.Db.Update("article", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("article_id")})
|
||||
}
|
||||
if data.GetCeilInt("notify_id") != 0 {
|
||||
that.Db.Update("notify", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("notify_id")})
|
||||
}
|
||||
if data.GetCeilInt("policy_id") != 0 {
|
||||
that.Db.Update("policy", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("policy_id")})
|
||||
}
|
||||
|
||||
if data.GetCeilInt("declare_id") != 0 {
|
||||
that.Db.Update("declare", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("declare_id")})
|
||||
}
|
||||
|
||||
if data.GetCeilInt("provider_id") != 0 {
|
||||
that.Db.Update("provider", Map{"favorite_num[#]": "favorite_num-1"}, Map{"id": data.GetCeilInt("provider_id")})
|
||||
}
|
||||
}
|
||||
|
||||
that.Display(0, "取消关注成功")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, "没有关注")
|
||||
return
|
||||
},
|
||||
|
||||
"search": func(that *Context) {
|
||||
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
tp := ObjToInt(that.Req.FormValue("type"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "user_id": that.Session("user_id").Data}
|
||||
|
||||
if tp != 0 {
|
||||
data["type"] = tp
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "ORDER": "modify_time DESC"}
|
||||
}
|
||||
|
||||
count := that.Db.Count("favorite", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("favorite", "*", data)
|
||||
|
||||
for _, v := range res {
|
||||
if v.GetCeilInt64("policy_id") != 0 {
|
||||
v["policy"] = that.Db.Get("policy", "id,tag", Map{"id": v.GetCeilInt64("policy_id")})
|
||||
}
|
||||
if v.GetCeilInt64("declare_id") != 0 {
|
||||
v["declare"] = that.Db.Get("declare", "id,money_scope_min,money_scope_max,status", Map{"id": v.GetCeilInt64("declare_id")})
|
||||
}
|
||||
|
||||
if v.GetCeilInt64("notify_id") != 0 {
|
||||
v["notify"] = that.Db.Get("notify", "id,tag", Map{"id": v.GetCeilInt64("notify_id")})
|
||||
}
|
||||
|
||||
if v.GetCeilInt64("article_id") != 0 {
|
||||
v["article"] = that.Db.Get("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
|
||||
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status", Map{"id": v.GetCeilInt64("article_id")})
|
||||
}
|
||||
|
||||
if v.GetCeilInt64("provider_id") != 0 {
|
||||
v["provider"] = that.Db.Get("provider", "id,name,level,discount,avatar,title,description,"+
|
||||
"click_num_base+click_num AS click_num,handle_num_base+handle_num AS handle_num,favorite_num_base+favorite_num AS favorite_num,modify_time", Map{"id": v.GetCeilInt64("provider_id")})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"code.hoteas.com/golang/hotime/common"
|
||||
"fmt"
|
||||
"github.com/tealeg/xlsx"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func DataToExcel(w http.ResponseWriter, r *http.Request, titleList []string, dataList []common.Map, fileName string) {
|
||||
// 生成一个新的文件
|
||||
file := xlsx.NewFile()
|
||||
// 添加sheet页
|
||||
sheet, _ := file.AddSheet("Sheet1")
|
||||
// 插入表头
|
||||
titleRow := sheet.AddRow()
|
||||
for _, v := range titleList {
|
||||
cell := titleRow.AddCell()
|
||||
cell.Value = v
|
||||
cell.GetStyle().Font.Color = "00FF0000"
|
||||
}
|
||||
for _, v1 := range dataList {
|
||||
row := sheet.AddRow()
|
||||
// 插入内容
|
||||
for _, v := range titleList {
|
||||
cell := row.AddCell()
|
||||
cell.SetValue(v1.Get(v))
|
||||
}
|
||||
|
||||
}
|
||||
//file.Save("D:\\temp\\vip_excel"+fileName)
|
||||
|
||||
fileName = fmt.Sprintf("%s.xlsx", fileName)
|
||||
//_ = file.Save(fileName)
|
||||
w.Header().Add("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName))
|
||||
w.Header().Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
|
||||
|
||||
var buffer bytes.Buffer
|
||||
_ = file.Write(&buffer)
|
||||
content := bytes.NewReader(buffer.Bytes())
|
||||
http.ServeContent(w, r, fileName, time.Now(), content)
|
||||
}
|
||||
+106
-133
@@ -3,152 +3,125 @@ package app
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Project 管理端项目
|
||||
var Project = Proj{
|
||||
"article": ArticleCtr,
|
||||
"company": CompanyCtr,
|
||||
"declare": DeclareCtr,
|
||||
"favorite": FavoriteCtr,
|
||||
"lxcx": Lxcx,
|
||||
"matters": MattersCtr,
|
||||
"notify": NotifyCtr,
|
||||
"order": OrderCtr,
|
||||
"policy": PolicyCtr,
|
||||
"provider": ProviderCtr,
|
||||
"search_record": SearchRecordCtr,
|
||||
"sms": Sms,
|
||||
"tag": TagCtr,
|
||||
"upan": UpanCtr,
|
||||
"user": UserCtr,
|
||||
"vip_order": VipOrderCtr,
|
||||
"websocket": WebsocketCtr,
|
||||
"wechath5": Wechath5,
|
||||
"wechatmini": Wechath5,
|
||||
"coupon": CouponCtr,
|
||||
}
|
||||
var AppProj = Proj{
|
||||
"article": ArticleCtr,
|
||||
"org": OrgCtr,
|
||||
"ctg": CtgCtr,
|
||||
"mail": MailCtr,
|
||||
"test": {
|
||||
"test": func(that *Context) {
|
||||
//data:=that.Db.Table("admin").Order("id DESC").Select("*")
|
||||
//data1:=that.Db.Table("admin").Where(Map{"name[~]":"m"}).Order("id DESC").Select("*")
|
||||
//
|
||||
//data3:=that.Db.Select("admin","*",Map{"name[~]":"m"})
|
||||
data2 := that.Db.Table("article").Where(Map{"title[~]": "m"}).Order("id DESC").Page(1, 10).Select("*")
|
||||
c := that.Db.Table("article").Where(Map{"title[~]": "m"}).Order("id DESC").Group("title").Select("*")
|
||||
//that.Display(0,Slice{data1,data,data3,data2})
|
||||
that.Display(0, Slice{data2, c})
|
||||
},
|
||||
"res": func(that *Context) {
|
||||
ebw_res := that.Db.Select("ebw_res", "*")
|
||||
|
||||
//生成随机码的6位md5
|
||||
func getSn() string {
|
||||
x := Rand(8)
|
||||
return Substr(Md5(ObjToStr(int64(x)+time.Now().UnixNano()+int64(Rand(6)))), 0, 6)
|
||||
}
|
||||
|
||||
//生成随机码的4位随机数
|
||||
func getCode() string {
|
||||
//res := ""
|
||||
//for i := 0; i < 4; i++ {
|
||||
res := ObjToStr(RandX(1000, 9999))
|
||||
//}
|
||||
return res
|
||||
}
|
||||
|
||||
func strToArray(str string) Slice {
|
||||
s := Slice{}
|
||||
|
||||
olds := strings.Split(str, ",")
|
||||
for _, v := range olds {
|
||||
if v != "" {
|
||||
s = append(s, v)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func arrayToStr(ars Slice) string {
|
||||
s := ","
|
||||
if ars == nil {
|
||||
return s
|
||||
}
|
||||
for k, _ := range ars {
|
||||
s = s + ars.GetString(k) + ","
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
//认证公共方案
|
||||
func auth(that *Context, phone, companyName, userName string) error {
|
||||
|
||||
user := that.Db.Get("user", "id,phone,salesman_id,company_id,provider_id,name", Map{"id": that.Session("user_id").ToCeilInt()})
|
||||
if user == nil {
|
||||
return errors.New("找不到用户")
|
||||
}
|
||||
company := that.Db.Get("company", "name,id", Map{"id": user.GetCeilInt("company_id")})
|
||||
|
||||
if company == nil {
|
||||
return errors.New("找不到企业")
|
||||
}
|
||||
//手机号与原来的不同则进行绑定
|
||||
if phone != user.GetString("phone") || companyName != company.GetString("name") || user.GetString("name") != userName {
|
||||
//微信验证成功
|
||||
if that.Session("wechat_phone").ToStr() == phone {
|
||||
that.Db.Update("user", Map{"phone": phone}, Map{"id": user.GetCeilInt("id")})
|
||||
if user.GetCeilInt("company_id") != 0 {
|
||||
that.Db.Update("company", Map{"phone": phone}, Map{"id": user.GetCeilInt("company_id")})
|
||||
for _, v := range ebw_res {
|
||||
data := Map{"id": v.GetCeilInt("id"), "name": v.GetString("name"),
|
||||
"parent_id": v.GetCeilInt64("pid"),
|
||||
"sn": v.GetString("url"), "create_time": time.Now().Format("2006-01-02 15:04"),
|
||||
"modify_time": time.Now().Format("2006-01-02 15:04"), "admin_id": 1}
|
||||
if data.GetCeilInt("parent_id") == 0 {
|
||||
data["parent_id"] = nil
|
||||
}
|
||||
that.Db.Insert("ctg", data)
|
||||
}
|
||||
user["phone"] = phone
|
||||
} else if that.Req.FormValue("code") == "" || that.Session("phone").ToStr() != phone || that.Session("code").ToStr() != that.Req.FormValue("code") {
|
||||
|
||||
return errors.New("验证码错误")
|
||||
} else {
|
||||
that.Db.Update("user", Map{"phone": phone, "name": userName}, Map{"id": user.GetCeilInt("id")})
|
||||
if user.GetCeilInt("company_id") != 0 {
|
||||
that.Db.Update("company", Map{"phone": phone}, Map{"id": user.GetCeilInt("company_id")})
|
||||
that.Db.Exec("UPDATE ctg SET parent_id =NULL WHERE parent_id=id")
|
||||
|
||||
ss(0, that)
|
||||
|
||||
that.Display(0, len(ebw_res))
|
||||
|
||||
},
|
||||
"news": func(that *Context) {
|
||||
ebw_news := that.Db.Select("ebw_news", "*")
|
||||
|
||||
for _, v := range ebw_news {
|
||||
ctg := that.Db.Get("ctg", "*", Map{"sn": v.GetString("type")})
|
||||
data := Map{"sn": v.GetString("id"), "title": v.GetString("title"),
|
||||
"content": v.GetString("content"), "push_time": v.GetString("timedate"),
|
||||
"author": v.GetString("owner"), "origin": v.GetString("source"), "click_num": v.GetString("readtime"),
|
||||
"sort": v.GetCeilInt("zhiding"), "create_time": time.Now().Format("2006-01-02 15:04"),
|
||||
"modify_time": time.Now().Format("2006-01-02 15:04"), "admin_id": 1}
|
||||
if ctg != nil {
|
||||
data["ctg_id"] = ctg.GetCeilInt("id")
|
||||
}
|
||||
that.Db.Insert("article", data)
|
||||
}
|
||||
user["phone"] = phone
|
||||
}
|
||||
|
||||
}
|
||||
//
|
||||
//company := that.Db.Get("company", "name,id", Map{"id": user.GetCeilInt("company_id")})
|
||||
if company != nil {
|
||||
that.Db.Update("company", Map{"name": companyName}, Map{"id": company.GetCeilInt64("id")})
|
||||
if user.GetCeilInt64("salesman_id") != 0 {
|
||||
that.Db.Update("user", Map{"certification_flag": 1}, Map{"id": user.GetCeilInt("id")})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
that.Display(0, len(ebw_news))
|
||||
|
||||
company = Map{"name": companyName,
|
||||
"user_id": user.GetCeilInt("id"),
|
||||
}
|
||||
if user.GetCeilInt("salesman_id") != 0 {
|
||||
company["salesman_id"] = user.GetCeilInt("salesman_id")
|
||||
}
|
||||
if user.GetCeilInt("provider_id") != 0 {
|
||||
company["provider_id"] = user.GetCeilInt("provider_id")
|
||||
}
|
||||
if user.GetString("phone") != "" {
|
||||
company["phone"] = user.GetString("phone")
|
||||
}
|
||||
company["id"] = that.Db.Insert("company", company)
|
||||
if company.GetCeilInt64("id") == 0 {
|
||||
return errors.New("新建企业失败")
|
||||
}
|
||||
upUser := Map{"company_id": company.GetCeilInt64("id")}
|
||||
if user.GetCeilInt64("salesman_id") != 0 {
|
||||
upUser["certification_flag"] = 1
|
||||
},
|
||||
"res2news": func(that *Context) {
|
||||
ebw_news_addition_res := that.Db.Select("ebw_news_addition_res", "*")
|
||||
|
||||
}
|
||||
that.Db.Update("user", upUser, Map{"id": that.Session("user_id").Data})
|
||||
for _, v := range ebw_news_addition_res {
|
||||
ctg := that.Db.Get("ctg", "*", Map{"sn": v.GetString("fk_res")})
|
||||
article := that.Db.Get("article", "*", Map{"sn": v.GetString("fk_newsid")})
|
||||
data := Map{"sn": Md5(ObjToStr(time.Now().UnixNano()) + ObjToStr(RandX(10000, 100000))),
|
||||
"create_time": time.Now().Format("2006-01-02 15:04"),
|
||||
"modify_time": time.Now().Format("2006-01-02 15:04"), "admin_id": 1}
|
||||
if ctg != nil {
|
||||
data["ctg_id"] = ctg.GetCeilInt("id")
|
||||
}
|
||||
if article != nil {
|
||||
data["article_id"] = article.GetCeilInt("id")
|
||||
}
|
||||
that.Db.Insert("ctg_article", data)
|
||||
}
|
||||
|
||||
return nil
|
||||
that.Display(0, len(ebw_news_addition_res))
|
||||
},
|
||||
//将文章没有关联的ctg_article进行关联
|
||||
"article": func(that *Context) {
|
||||
articles := that.Db.Select("article", "id,ctg_id")
|
||||
for _, v := range articles {
|
||||
ctg_article := that.Db.Get("ctg_article", "id", Map{"article_id": v.GetCeilInt("id")})
|
||||
if ctg_article == nil {
|
||||
|
||||
data := Map{"sn": Md5(ObjToStr(time.Now().UnixNano()) + ObjToStr(RandX(10000, 100000))),
|
||||
"create_time": time.Now().Format("2006-01-02 15:04"),
|
||||
"modify_time": time.Now().Format("2006-01-02 15:04"), "admin_id": 1}
|
||||
if v.GetCeilInt("ctg_id") == 0 || v.GetCeilInt("id") == 0 {
|
||||
continue
|
||||
}
|
||||
data["ctg_id"] = v.GetCeilInt("ctg_id")
|
||||
data["article_id"] = v.GetCeilInt("id")
|
||||
that.Db.Insert("ctg_article", data)
|
||||
}
|
||||
|
||||
}
|
||||
that.Display(0, len(articles))
|
||||
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// FilterEmoji 过滤 emoji 表情
|
||||
func FilterEmoji(content string) string {
|
||||
new_content := ""
|
||||
for _, value := range content {
|
||||
_, size := utf8.DecodeRuneInString(string(value))
|
||||
if size <= 3 {
|
||||
new_content += string(value)
|
||||
}
|
||||
func ss(parent_id int, that *Context) {
|
||||
var ctgs []Map
|
||||
ctg := that.Db.Get("ctg", "*", Map{"id": parent_id})
|
||||
if parent_id == 0 {
|
||||
ctgs = that.Db.Select("ctg", "*", Map{"parent_id": nil})
|
||||
} else {
|
||||
ctgs = that.Db.Select("ctg", "*", Map{"parent_id": parent_id})
|
||||
}
|
||||
|
||||
for _, v := range ctgs {
|
||||
if ctg == nil {
|
||||
ctg = Map{"parent_ids": ","}
|
||||
}
|
||||
ids := ctg.GetString("parent_ids") + ObjToStr(v.GetCeilInt("id")) + ","
|
||||
that.Db.Update("ctg", Map{"parent_ids": ids}, Map{"id": v.GetCeilInt("id")})
|
||||
ss(v.GetCeilInt("id"), that)
|
||||
}
|
||||
return new_content
|
||||
}
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
"code.hoteas.com/golang/hotime/common"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
var Lxcx = Ctr{
|
||||
"lists": func(that *Context) {
|
||||
urlStr := "https://www.ruichuangshe.com/Resources/Services/sAppInterface.ashx?type=policyprojectbycompanyname&page=1&pagesize=10&code=8eb68adf79d660e57ccd69ea4bf340162e29e43ec344df62b364bd65b886da7fca9fb995ad93a5b485d66fd268f946f34cf0&CompanyName="
|
||||
companyName := that.Req.FormValue("company")
|
||||
companyName = url.QueryEscape(url.QueryEscape(companyName))
|
||||
|
||||
resp, err := http.Get(urlStr + companyName)
|
||||
if err != nil {
|
||||
log.Println("err")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Println("err")
|
||||
}
|
||||
that.Display(0, common.ObjToMap(string(b)))
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"time"
|
||||
)
|
||||
|
||||
var MailCtr = Ctr{
|
||||
"add": func(that *Context) {
|
||||
title := that.Req.FormValue("title")
|
||||
name := that.Req.FormValue("name")
|
||||
phone := that.Req.FormValue("phone")
|
||||
content := that.Req.FormValue("content")
|
||||
|
||||
tp := ObjToInt(that.Req.FormValue("type"))
|
||||
show := ObjToInt(that.Req.FormValue("show"))
|
||||
|
||||
if len(title) < 5 {
|
||||
that.Display(3, "标题过短")
|
||||
return
|
||||
}
|
||||
if len(name) < 2 {
|
||||
that.Display(3, "姓名错误")
|
||||
return
|
||||
}
|
||||
if len(phone) < 8 {
|
||||
that.Display(3, "联系方式错误")
|
||||
return
|
||||
}
|
||||
if len(content) < 10 {
|
||||
that.Display(3, "内容过短")
|
||||
return
|
||||
}
|
||||
|
||||
data := Map{
|
||||
"sn": Md5(ObjToStr(time.Now().UnixNano()) + ObjToStr(RandX(10000, 100000))),
|
||||
"name": name, "title": title, "phone": phone, "content": content, "type": tp, "show": show,
|
||||
"modify_time[#]": "NOW()", "create_time[#]": "NOW()",
|
||||
}
|
||||
id := that.Db.Insert("mail", data)
|
||||
if id == 0 {
|
||||
that.Display(4, "创建失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, "成功")
|
||||
return
|
||||
|
||||
},
|
||||
"info": func(that *Context) {
|
||||
sn := that.Req.FormValue("sn")
|
||||
|
||||
mail := that.Db.Get("mail", "*", Map{"sn": sn})
|
||||
|
||||
that.Display(0, mail)
|
||||
},
|
||||
"list": func(that *Context) {
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page == 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize == 0 {
|
||||
pageSize = 10
|
||||
}
|
||||
|
||||
//keywords:=that.Req.FormValue("keywords")
|
||||
|
||||
//sort:=that.Req.FormValue("sort")
|
||||
|
||||
where := Map{"state": 0, "show": 1}
|
||||
|
||||
//if keywords!=""{
|
||||
// where["OR"]=Map{"title[~]":keywords,"description[~]":keywords,"author[~]":keywords,"sn[~]":keywords,"origin[~]":keywords,"url[~]":keywords}
|
||||
//}
|
||||
|
||||
if len(where) > 1 {
|
||||
where = Map{"AND": where}
|
||||
}
|
||||
|
||||
//if sort==""{
|
||||
// where["ORDER"]=Slice{"sort DESC","push_time DESC"}
|
||||
//}
|
||||
//
|
||||
//if sort=="time"{
|
||||
where["ORDER"] = "create_time DESC"
|
||||
//}
|
||||
count := that.Db.Count("mail", where)
|
||||
mail := that.Db.Page(page, pageSize).PageSelect("mail", "*", where)
|
||||
|
||||
that.Display(0, Map{"count": count, "data": mail})
|
||||
|
||||
},
|
||||
}
|
||||
@@ -1,168 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var MattersCtr = Ctr{
|
||||
"create": func(that *Context) {
|
||||
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
sn := that.Req.FormValue("sn")
|
||||
if sn == "" {
|
||||
that.Display(3, "没有SN码")
|
||||
return
|
||||
}
|
||||
serviceContent := that.Req.FormValue("service_content")
|
||||
if serviceContent == "" {
|
||||
that.Display(3, "没有服务内容")
|
||||
return
|
||||
}
|
||||
|
||||
salesman := that.Db.Get("salesman", "id,provider_id,name,nickname", Map{"AND": Map{"sn": sn, "del_flag": 0}})
|
||||
if salesman == nil {
|
||||
that.Display(4, "找不到服务商")
|
||||
return
|
||||
}
|
||||
|
||||
re := that.Db.Insert("matters", Map{
|
||||
"user_id": that.Session("user_id").Data,
|
||||
"salesman_id": salesman.GetCeilInt64("id"),
|
||||
"provider_id": salesman.GetCeilInt64("provider_id"),
|
||||
"type": 1,
|
||||
"service_content": serviceContent,
|
||||
"complete_flag": 0,
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
})
|
||||
res := that.Db.Get("matters", "*", Map{"id": re})
|
||||
if res == nil {
|
||||
that.Display(4, "找不到事项")
|
||||
return
|
||||
}
|
||||
|
||||
res["salesman"] = that.Db.Get("salesman", "name,id", Map{"id": res.GetCeilInt64("salesman_id")})
|
||||
|
||||
res["provider"] = that.Db.Get("provider", "name,id", Map{"id": res.GetCeilInt64("provider_id")})
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
"info": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("matters", "*", Map{"id": id})
|
||||
if res == nil {
|
||||
that.Display(4, "找不到事项")
|
||||
return
|
||||
}
|
||||
|
||||
res["salesman"] = that.Db.Get("salesman", "name,id", Map{"id": res.GetCeilInt64("salesman_id")})
|
||||
|
||||
res["provider"] = that.Db.Get("provider", "name,id", Map{"id": res.GetCeilInt64("provider_id")})
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
"edit": func(that *Context) {
|
||||
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
serviceEvaluation := ObjToInt(that.Req.FormValue("service_evaluation"))
|
||||
evaluationRemark := that.Req.FormValue("evaluation_remark")
|
||||
|
||||
if serviceEvaluation == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
matters := that.Db.Get("matters", "*", Map{"AND": Map{"id": id, "user_id": that.Session("user_id").Data}})
|
||||
if matters == nil {
|
||||
that.Display(4, "不是属于你的评价")
|
||||
return
|
||||
}
|
||||
|
||||
if matters.GetCeilInt("complete_flag") == 1 {
|
||||
that.Display(4, "已完成评价,不可重复评价")
|
||||
return
|
||||
}
|
||||
|
||||
that.Db.Update("matters", Map{"service_evaluation": serviceEvaluation, "evaluation_remark": evaluationRemark, "complete_flag": 1, "modify_time[#]": "now()"}, Map{"id": id})
|
||||
|
||||
that.Display(0, "评价成功")
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
tp := that.Req.FormValue("type")
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "user_id": that.Session("user_id").Data}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
|
||||
}
|
||||
|
||||
if tp != "" {
|
||||
data["type"] = ObjToInt(tp)
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["modify_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["modify_time[<=]"] = finishTime
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "ORDER": "modify_time DESC"}
|
||||
}
|
||||
|
||||
count := that.Db.Count("matters", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("matters", "*", data)
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var NotifyCtr = Ctr{
|
||||
|
||||
"info": func(that *Context) {
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("notify", "*", Map{"id": id})
|
||||
|
||||
if res == nil {
|
||||
that.Display(4, "找不到通知公告")
|
||||
return
|
||||
}
|
||||
res["click_num"] = res.GetCeilInt64("click_num") + res.GetCeilInt64("click_num_base") + 1
|
||||
delete(res, "click_num_base")
|
||||
|
||||
res["favorite_num"] = res.GetCeilInt64("favorite_num") + res.GetCeilInt64("favorite_num_base")
|
||||
delete(res, "favorite_num_base")
|
||||
|
||||
article := that.Db.Get("article", "*", Map{"id": res.GetCeilInt64("article_id")})
|
||||
if article != nil {
|
||||
article["click_num"] = article.GetCeilInt64("click_num") + article.GetCeilInt64("click_num_base") + 1
|
||||
delete(article, "click_num_base")
|
||||
|
||||
article["favorite_num"] = article.GetCeilInt64("favorite_num") + article.GetCeilInt64("favorite_num_base")
|
||||
delete(article, "favorite_num_base")
|
||||
}
|
||||
|
||||
res["article"] = article
|
||||
//浏览量加1
|
||||
that.Db.Update("notify", Map{"click_num[#]": "click_num+1"}, Map{"id": id})
|
||||
//浏览量加1
|
||||
that.Db.Update("article", Map{"click_num[#]": "click_num+1"}, Map{"id": res.GetCeilInt64("article_id")})
|
||||
|
||||
//查询是否已关注
|
||||
if that.Session("user_id").Data != nil {
|
||||
favorite := that.Db.Get("favorite", "user_id,notify_id", Map{"AND": Map{"notify_id": id, "user_id": that.Session("user_id").ToCeilInt(), "del_flag": 0}})
|
||||
res["favorite"] = favorite
|
||||
}
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "notify_id[!]": nil}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["release_date[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["release_date[<=]"] = finishTime
|
||||
}
|
||||
|
||||
dispatchName := that.Req.FormValue("dispatch_name")
|
||||
if dispatchName != "" {
|
||||
data["dispatch_name"] = dispatchName
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "ORDER": "release_time DESC"}
|
||||
}
|
||||
|
||||
count := that.Db.Count("article", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
|
||||
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status,policy_id,declare_id,notify_id,dispatch_name,policy_level", data)
|
||||
for _, v := range res {
|
||||
|
||||
if v.GetCeilInt("notify_id") > 0 {
|
||||
v["notify"] = that.Db.Get("notify", "id,tag", Map{"id": v.GetCeilInt("notify_id")})
|
||||
}
|
||||
//if v.GetCeilInt("policy_id")>0{
|
||||
// v["policy"]=that.Db.Get("policy","tag",Map{"id":v.GetCeilInt("policy_id")})
|
||||
//}
|
||||
//if v.GetCeilInt("declare_id")>0{
|
||||
// v["declare"]=that.Db.Get("declare","money_scope_min,money_scope_max,tag,status",Map{"id":v.GetCeilInt("declare_id")})
|
||||
//}
|
||||
}
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"time"
|
||||
)
|
||||
|
||||
var OrderCtr = Ctr{
|
||||
//创建订单
|
||||
"create": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
providerId := ObjToInt(that.Req.FormValue("provider_id"))
|
||||
phone := that.Req.FormValue("phone")
|
||||
companyName := that.Req.FormValue("company_name")
|
||||
userName := that.Req.FormValue("user_name")
|
||||
if providerId == 0 || len(phone) != 11 || len(companyName) < 4 || len(userName) < 2 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
err := auth(that, phone, companyName, userName)
|
||||
if err != nil {
|
||||
that.Display(3, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
declareId := ObjToInt(that.Req.FormValue("declare_id"))
|
||||
|
||||
tp := that.Req.FormValue("type")
|
||||
|
||||
//新建流程
|
||||
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").Data})
|
||||
|
||||
if user == nil {
|
||||
that.Display(4, "找不到用户")
|
||||
return
|
||||
}
|
||||
company := that.Db.Get("company", "name", Map{"id": user.GetCeilInt("company_id")})
|
||||
if company == nil {
|
||||
that.Display(4, "找不到企业")
|
||||
return
|
||||
}
|
||||
|
||||
provider := that.Db.Get("provider", "*", Map{"id": providerId})
|
||||
|
||||
if provider == nil {
|
||||
that.Display(4, "找不到该服务商")
|
||||
return
|
||||
}
|
||||
|
||||
//是否以前已经创建了该服务商的订单,如果创建了则直接跳转到订单详情中去
|
||||
oldOrder := that.Db.Get("order", "id", Map{"AND": Map{"provider_id": providerId, "user_id": that.Session("user_id").Data, "del_flag": 0, "status": 0}})
|
||||
if oldOrder != nil {
|
||||
orderRecord := Map{
|
||||
"order_id": oldOrder.GetCeilInt64("id"),
|
||||
"user_id": user.GetCeilInt64("id"),
|
||||
"remarks": user.GetString("nickname") + "向“" + provider.GetString("name") + "”服务商再次发起了订单请求",
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
}
|
||||
|
||||
orderRecord["id"] = that.Db.Insert("order_record", orderRecord)
|
||||
that.Db.Update("order", Map{"order_record_id": orderRecord.GetCeilInt64("id"), "modify_time[#]": "now()"}, Map{"id": oldOrder.GetCeilInt64("id")})
|
||||
|
||||
that.Display(0, oldOrder.GetCeilInt64("id"))
|
||||
return
|
||||
}
|
||||
|
||||
data := Map{
|
||||
"name": "购买“" + provider.GetString("title") + "”服务",
|
||||
"sn": "SN" + time.Now().Format("20060102150405") + getSn(),
|
||||
"user_id": user.GetCeilInt64("id"),
|
||||
"salesman_id": provider.GetCeilInt64("salesman_id"),
|
||||
"provider_id": provider.GetCeilInt64("id"),
|
||||
"company_id": company.GetCeilInt64("id"),
|
||||
"company_name": company.GetString("name"),
|
||||
"phone": user.GetString("phone"),
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
}
|
||||
|
||||
if declareId != 0 {
|
||||
data["policy_declare_flag"] = 1
|
||||
data["declare_id"] = declareId
|
||||
}
|
||||
|
||||
if tp == "policy_declare_flag" {
|
||||
data["policy_declare_flag"] = 1
|
||||
}
|
||||
|
||||
data["id"] = that.Db.Insert("order", data)
|
||||
if data.GetCeilInt64("id") == 0 {
|
||||
that.Display(4, "无法生成订单!")
|
||||
return
|
||||
}
|
||||
|
||||
orderRecord := Map{
|
||||
"order_id": data["id"],
|
||||
"user_id": user.GetCeilInt64("id"),
|
||||
"remarks": user.GetString("nickname") + "向“" + provider.GetString("name") + "”服务商发起了订单请求",
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
}
|
||||
|
||||
orderRecord["id"] = that.Db.Insert("order_record", orderRecord)
|
||||
|
||||
if orderRecord.GetCeilInt64("id") == 0 {
|
||||
that.Display(4, "无法生成订单记录!")
|
||||
return
|
||||
}
|
||||
|
||||
that.Db.Update("order", Map{"order_record_id": orderRecord.GetCeilInt64("id")}, Map{"id": data.GetCeilInt64("id")})
|
||||
|
||||
that.Display(0, data.GetCeilInt64("id"))
|
||||
},
|
||||
|
||||
"info": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("order", "*", Map{"AND": Map{"id": id, "user_id": that.Session("user_id").Data}})
|
||||
|
||||
if res == nil {
|
||||
that.Display(4, "找不到对应订单")
|
||||
return
|
||||
}
|
||||
if res.GetCeilInt("provider_id") > 0 {
|
||||
res["provider"] = that.Db.Get("provider", "name,title,phone", Map{"id": res.GetCeilInt("provider_id")})
|
||||
}
|
||||
|
||||
res["order_record"] = that.Db.Select("order_record", "remarks,modify_time", Map{"order_id": res.GetCeilInt("id"), "ORDER": "modify_time DESC"})
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "user_id": that.Session("user_id").Data}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"sn[~]": keywords, "company_name[~]": keywords, "name[~]": keywords}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["modify_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["modify_time[<=]"] = finishTime
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "ORDER": "modify_time DESC"}
|
||||
}
|
||||
|
||||
count := that.Db.Count("order", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("order", "*", data)
|
||||
for _, v := range res {
|
||||
|
||||
//if v.GetCeilInt("policy_id")>0{
|
||||
// v["policy"]=that.Db.Get("policy","id,tag",Map{"id":v.GetCeilInt("policy_id")})
|
||||
//}
|
||||
if v.GetCeilInt("provider_id") > 0 {
|
||||
v["provider"] = that.Db.Get("provider", "name,title", Map{"id": v.GetCeilInt("provider_id")})
|
||||
}
|
||||
if v.GetCeilInt("order_record_id") > 0 {
|
||||
v["order_record"] = that.Db.Get("order_record", "remarks,modify_time", Map{"id": v.GetCeilInt("order_record_id")})
|
||||
}
|
||||
}
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"time"
|
||||
)
|
||||
|
||||
var OrgCtr = Ctr{
|
||||
"info": func(that *Context) {
|
||||
sn := that.Req.FormValue("sn")
|
||||
article := that.Db.Get("article", "*", Map{"sn": sn})
|
||||
that.Display(0, article)
|
||||
},
|
||||
"list": func(that *Context) {
|
||||
sn := that.Req.FormValue("sn") //orgsn
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page == 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize == 0 {
|
||||
pageSize = 50
|
||||
}
|
||||
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
|
||||
sort := that.Req.FormValue("sort")
|
||||
|
||||
where := Map{"push_time[<=]": time.Now().Format("2006-01-02 15:04"), "state": 0}
|
||||
if sn != "" {
|
||||
org := that.Db.Get("org", "id", Map{"sn": sn})
|
||||
if org != nil {
|
||||
where["org_id"] = org.GetCeilInt("id")
|
||||
}
|
||||
}
|
||||
|
||||
if keywords != "" {
|
||||
where["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "author[~]": keywords, "sn[~]": keywords, "origin[~]": keywords, "url[~]": keywords}
|
||||
}
|
||||
|
||||
if len(where) > 1 {
|
||||
where = Map{"AND": where}
|
||||
}
|
||||
|
||||
if sort == "" {
|
||||
where["ORDER"] = Slice{"sort DESC", "id DESC"}
|
||||
}
|
||||
|
||||
if sort == "time" {
|
||||
where["ORDER"] = "push_time DESC"
|
||||
}
|
||||
|
||||
article := that.Db.Page(page, pageSize).PageSelect("article", "sn,title,description,push_time,lunbo,author,origin,url", where)
|
||||
|
||||
that.Display(0, article)
|
||||
|
||||
},
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var PolicyCtr = Ctr{
|
||||
|
||||
"info": func(that *Context) {
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("policy", "*", Map{"id": id})
|
||||
|
||||
if res == nil {
|
||||
that.Display(4, "找不到通知公告")
|
||||
return
|
||||
}
|
||||
res["click_num"] = res.GetCeilInt64("click_num") + res.GetCeilInt64("click_num_base") + 1
|
||||
delete(res, "click_num_base")
|
||||
|
||||
res["favorite_num"] = res.GetCeilInt64("favorite_num") + res.GetCeilInt64("favorite_num_base")
|
||||
delete(res, "favorite_num_base")
|
||||
|
||||
article := that.Db.Get("article", "*", Map{"id": res.GetCeilInt64("article_id")})
|
||||
if article != nil {
|
||||
article["click_num"] = article.GetCeilInt64("click_num") + article.GetCeilInt64("click_num_base") + 1
|
||||
delete(article, "click_num_base")
|
||||
|
||||
article["favorite_num"] = article.GetCeilInt64("favorite_num") + article.GetCeilInt64("favorite_num_base")
|
||||
delete(article, "favorite_num_base")
|
||||
}
|
||||
|
||||
res["article"] = article
|
||||
|
||||
//浏览量加1
|
||||
that.Db.Update("policy", Map{"click_num[#]": "click_num+1"}, Map{"id": id})
|
||||
//浏览量加1
|
||||
that.Db.Update("article", Map{"click_num[#]": "click_num+1"}, Map{"id": res.GetCeilInt64("article_id")})
|
||||
|
||||
//查询是否已关注
|
||||
if that.Session("user_id").Data != nil {
|
||||
favorite := that.Db.Get("favorite", "user_id,policy_id", Map{"AND": Map{"policy_id": id, "user_id": that.Session("user_id").ToCeilInt(), "del_flag": 0}})
|
||||
res["favorite"] = favorite
|
||||
}
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "policy_id[!]": nil}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["release_date[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["release_date[<=]"] = finishTime
|
||||
}
|
||||
|
||||
dispatchName := that.Req.FormValue("dispatch_name")
|
||||
if dispatchName != "" {
|
||||
data["dispatch_name"] = dispatchName
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "ORDER": "release_time DESC"}
|
||||
}
|
||||
|
||||
count := that.Db.Count("article", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
|
||||
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status,policy_id,declare_id,policy_id,dispatch_name,policy_level", data)
|
||||
for _, v := range res {
|
||||
|
||||
//if v.GetCeilInt("policy_id")>0{
|
||||
// v["policy"]=that.Db.Get("policy","id,tag",Map{"id":v.GetCeilInt("policy_id")})
|
||||
//}
|
||||
if v.GetCeilInt("policy_id") > 0 {
|
||||
v["policy"] = that.Db.Get("policy", "tag", Map{"id": v.GetCeilInt("policy_id")})
|
||||
}
|
||||
//if v.GetCeilInt("declare_id")>0{
|
||||
// v["declare"]=that.Db.Get("declare","money_scope_min,money_scope_max,tag,status",Map{"id":v.GetCeilInt("declare_id")})
|
||||
//}
|
||||
}
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var ProviderCtr = Ctr{
|
||||
//用户微信公众号或者小程序登录
|
||||
"info": func(that *Context) {
|
||||
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("provider", "*", Map{"id": id})
|
||||
|
||||
if res == nil {
|
||||
that.Display(4, "找不到服务商")
|
||||
return
|
||||
}
|
||||
|
||||
//浏览量加1
|
||||
that.Db.Update("provider", Map{"click_num[#]": "click_num+1"}, Map{"id": id})
|
||||
|
||||
//查询是否已关注
|
||||
if that.Session("user_id").Data != nil {
|
||||
favorite := that.Db.Get("favorite", "user_id,provider_id", Map{"AND": Map{"provider_id": id, "user_id": that.Session("user_id").ToCeilInt(), "del_flag": 0}})
|
||||
res["favorite"] = favorite
|
||||
}
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
"search": func(that *Context) {
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "state": 0}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"name[~]": keywords, "title[~]": keywords}
|
||||
}
|
||||
|
||||
tp := that.Req.FormValue("type")
|
||||
if tp != "" {
|
||||
data[tp] = 1
|
||||
}
|
||||
|
||||
policyDeclareFlag := that.Req.FormValue("policy_declare_flag")
|
||||
if policyDeclareFlag != "" {
|
||||
data["policy_declare_flag"] = ObjToInt(policyDeclareFlag)
|
||||
}
|
||||
|
||||
intellectualPropertyFlag := that.Req.FormValue("intellectual_property_flag")
|
||||
if intellectualPropertyFlag != "" {
|
||||
data["intellectual_property_flag"] = ObjToInt(intellectualPropertyFlag)
|
||||
}
|
||||
|
||||
taxOnsultingFlag := that.Req.FormValue("tax_onsulting_flag")
|
||||
if taxOnsultingFlag != "" {
|
||||
data["tax_onsulting_flag"] = ObjToInt(taxOnsultingFlag)
|
||||
}
|
||||
|
||||
lawFlag := that.Req.FormValue("law_flag")
|
||||
if lawFlag != "" {
|
||||
data["law_flag"] = ObjToInt(lawFlag)
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "ORDER": "id DESC"}
|
||||
}
|
||||
|
||||
count := that.Db.Count("provider", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("provider", "id,name,level,discount,avatar,title,description,"+
|
||||
"click_num_base+click_num AS click_num,handle_num_base+handle_num AS handle_num,favorite_num_base+favorite_num AS favorite_num,modify_time,policy_declare_flag,intellectual_property_flag,tax_onsulting_flag,law_flag", data)
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var SearchRecordCtr = Ctr{
|
||||
|
||||
"search": func(that *Context) {
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
//if pageSize <= 0 {
|
||||
pageSize = 50
|
||||
//}
|
||||
|
||||
data := Map{"del_flag": 0}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["search_company_name[~]"] = keywords
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["create_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["create_time[<=]"] = finishTime
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data}
|
||||
} else {
|
||||
data["ORDER"] = "create_time DESC"
|
||||
}
|
||||
|
||||
count := that.Db.Count("search_record", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("search_record", "id,search_company_name,policy_match_count,money_scope,create_time", data)
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
|
||||
},
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
"code.hoteas.com/golang/hotime/dri/ddsms"
|
||||
)
|
||||
|
||||
var Sms = Ctr{
|
||||
//只允许微信验证过的或者登录成功的发送短信
|
||||
"send": func(that *Context) {
|
||||
|
||||
if that.Session("wechat_id").Data == nil && that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录不可发送短信")
|
||||
return
|
||||
}
|
||||
|
||||
phone := that.Req.FormValue("phone")
|
||||
if len(phone) < 11 {
|
||||
that.Display(3, "手机号格式错误")
|
||||
return
|
||||
}
|
||||
code := getCode()
|
||||
that.Session("phone", phone)
|
||||
that.Session("code", code)
|
||||
|
||||
ddsms.DDY.SendYZM(phone, that.Config.GetString("smsLogin"), map[string]string{"code": code})
|
||||
|
||||
that.Display(0, "发送成功")
|
||||
},
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var TagCtr = Ctr{
|
||||
|
||||
"create": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
name := that.Req.FormValue("name")
|
||||
|
||||
oldTag := that.Db.Get("tag", "id", Map{"name": name})
|
||||
if oldTag != nil {
|
||||
that.Display(4, "此标签已存在")
|
||||
return
|
||||
}
|
||||
|
||||
re := that.Db.Insert("tag", Map{
|
||||
"user_id": that.Session("user_id").Data,
|
||||
"name": name,
|
||||
"remark": "用户上传",
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"state": 1, //先置为异常状态,等待审核通过
|
||||
"del_flag": 0,
|
||||
})
|
||||
|
||||
if re == 0 {
|
||||
that.Display(4, "添加失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, "添加成功")
|
||||
return
|
||||
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 40
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "state": 0}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"name[~]": keywords, "remark[~]": keywords}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["modify_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["modify_time[<=]"] = finishTime
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data}
|
||||
}
|
||||
|
||||
count := that.Db.Count("tag", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("tag", "id,name,remark", data)
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
"code.hoteas.com/golang/hotime/common"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var UpanCtr = Ctr{
|
||||
"login": func(that *Context) {
|
||||
timestamp := that.Req.FormValue("timestamp")
|
||||
sn := that.Req.FormValue("sn")
|
||||
|
||||
//str,_:=EnPwdCode([]byte(lus[len(lus)-1]+":"+ObjToStr(t)))//
|
||||
re, e := DePwdCode(sn)
|
||||
|
||||
if e != nil {
|
||||
that.Display(3, "数据异常")
|
||||
return
|
||||
}
|
||||
reStr := string(re)
|
||||
realSn := strings.Replace(reStr, ":"+timestamp, "", -1)
|
||||
if len(realSn)+len(timestamp)+1 != len(reStr) {
|
||||
that.Display(4, "数据验证失败")
|
||||
return
|
||||
}
|
||||
fmt.Println("U盘校验", realSn)
|
||||
user := that.Db.Get("user", "*", common.Map{"upankey": realSn})
|
||||
if user == nil {
|
||||
that.Display(5, "还没有绑定用户")
|
||||
return
|
||||
}
|
||||
|
||||
that.Session("user_id", user.GetCeilInt("id"))
|
||||
that.Display(0, "登录成功")
|
||||
},
|
||||
|
||||
"create": func(that *Context) {
|
||||
timestamp := that.Req.FormValue("timestamp")
|
||||
sn := that.Req.FormValue("sn")
|
||||
|
||||
//str,_:=EnPwdCode([]byte(lus[len(lus)-1]+":"+ObjToStr(t)))//
|
||||
re, e := DePwdCode(sn)
|
||||
|
||||
if e != nil {
|
||||
fmt.Println(e)
|
||||
that.Display(3, "数据异常")
|
||||
return
|
||||
}
|
||||
reStr := string(re)
|
||||
realSn := strings.Replace(reStr, ":"+timestamp, "", -1)
|
||||
if len(realSn)+len(timestamp)+1 != len(reStr) {
|
||||
that.Display(4, "数据验证失败")
|
||||
return
|
||||
}
|
||||
|
||||
fmt.Println("U盘校验", realSn)
|
||||
|
||||
uuser := that.Db.Get("user", "id", common.Map{"upankey": realSn})
|
||||
|
||||
if uuser != nil {
|
||||
that.Display(4, "已经绑定了其他企业")
|
||||
return
|
||||
}
|
||||
|
||||
phone := that.Req.FormValue("phone")
|
||||
companyName := that.Req.FormValue("company_name")
|
||||
userName := that.Req.FormValue("user_name")
|
||||
|
||||
if len(phone) != 11 || len(companyName) < 4 || len(userName) < 2 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
//验证不成功则反馈
|
||||
err := auth(that, phone, companyName, userName)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
that.Display(3, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
num := that.Db.Update("user", common.Map{"upankey": realSn}, common.Map{"id": that.Session("user_id").Data})
|
||||
if num == 0 {
|
||||
that.Display(4, "更新失败")
|
||||
return
|
||||
}
|
||||
that.Display(0, "绑定成功")
|
||||
|
||||
},
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var UserCtr = Ctr{
|
||||
"test": func(that *Context) {
|
||||
that.Session("user_id", 1)
|
||||
that.Session("wechat_id", 1)
|
||||
that.Display(0, 1)
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"info": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").ToCeilInt()})
|
||||
if user == nil {
|
||||
that.Display(2, "获取个人信息失败")
|
||||
return
|
||||
}
|
||||
|
||||
if user.GetCeilInt("company_id") == 0 {
|
||||
companyId := that.Db.Insert("company", Map{
|
||||
"user_id": user["id"],
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
})
|
||||
user["company_id"] = companyId
|
||||
that.Db.Update("user", Map{"company_id": companyId}, Map{"id": user.GetCeilInt("id")})
|
||||
}
|
||||
|
||||
delete(user, "password")
|
||||
|
||||
company := that.Db.Get("company", "id,name,social_code,business_license", Map{"id": user.GetCeilInt("company_id")})
|
||||
salesman := that.Db.Get("salesman", "id,name", Map{"id": user.GetCeilInt("salesman_id")})
|
||||
provider := that.Db.Get("provider", "id,name", Map{"id": user.GetCeilInt("provider_id")})
|
||||
|
||||
if user != nil {
|
||||
user["company"] = company
|
||||
user["salesman"] = salesman
|
||||
user["provider"] = provider
|
||||
}
|
||||
|
||||
that.Display(0, user)
|
||||
},
|
||||
|
||||
"edit": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
name := that.Req.FormValue("name")
|
||||
nickname := that.Req.FormValue("nickname")
|
||||
sex := that.Req.FormValue("sex")
|
||||
email := that.Req.FormValue("email")
|
||||
avatar := that.Req.FormValue("avatar")
|
||||
address := that.Req.FormValue("address")
|
||||
phone := that.Req.FormValue("phone") //如果更换手机号则要有新的短信验证码
|
||||
code := that.Req.FormValue("code")
|
||||
|
||||
data := Map{"modify_time[#]": "now()"}
|
||||
if name != "" {
|
||||
data["name"] = name
|
||||
}
|
||||
if nickname != "" {
|
||||
data["nickname"] = nickname
|
||||
}
|
||||
if sex != "" {
|
||||
data["sex"] = sex
|
||||
}
|
||||
if email != "" {
|
||||
data["email"] = email
|
||||
}
|
||||
if avatar != "" {
|
||||
data["avatar"] = avatar
|
||||
}
|
||||
if address != "" {
|
||||
data["address"] = address
|
||||
}
|
||||
if phone != "" {
|
||||
|
||||
//微信验证成功
|
||||
if that.Session("wechat_phone").ToStr() == phone {
|
||||
data["phone"] = phone
|
||||
} else if code == "" || that.Session("phone").ToStr() != phone || that.Session("code").ToStr() != code {
|
||||
that.Display(3, "手机短信验证失败")
|
||||
return
|
||||
}
|
||||
data["phone"] = phone
|
||||
}
|
||||
|
||||
re := that.Db.Update("user", data, Map{"id": that.Session("user_id").Data})
|
||||
if re == 0 {
|
||||
that.Display(4, "更新失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, "修改成功")
|
||||
},
|
||||
}
|
||||
@@ -1,235 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"code.hoteas.com/golang/hotime/dri/wechat"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
var VipOrderCtr = Ctr{
|
||||
//创建V订单
|
||||
"create": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
phone := that.Req.FormValue("phone")
|
||||
companyName := that.Req.FormValue("company_name")
|
||||
userName := that.Req.FormValue("user_name")
|
||||
if len(phone) != 11 || len(companyName) < 4 || len(userName) < 2 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
that.Db.Delete("vip_order", Map{"AND": Map{"user_id": that.Session("user_id").Data, "status": 0}})
|
||||
|
||||
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").Data})
|
||||
if user == nil {
|
||||
that.Display(2, "找不到此用户")
|
||||
return
|
||||
}
|
||||
|
||||
wc := that.Db.Get("wechat", "openid", Map{"AND": Map{"appid": that.Config.GetString("wechatAppID"), "user_id": that.Session("user_id").Data}})
|
||||
if wc == nil {
|
||||
that.Display(2, "没有获取微信个人信息")
|
||||
return
|
||||
}
|
||||
|
||||
err := auth(that, phone, companyName, userName)
|
||||
|
||||
if err != nil {
|
||||
that.Display(3, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
data := Map{
|
||||
"sn": "SN" + time.Now().Format("20060102150405") + getSn(),
|
||||
//"name":"1年VIP会员",
|
||||
"amount": 36000, //720元
|
||||
"user_id": user.GetCeilInt64("id"),
|
||||
"company_id": user.GetCeilInt("company_id"),
|
||||
"expiration_time": time.Now().Add(365 * 24 * time.Hour).Format("2006-01-02 15:04:05"),
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
"status": 0,
|
||||
}
|
||||
tp := "购买"
|
||||
if user.GetString("expiration_time") != "" {
|
||||
data["old_expiration_time"] = user.GetString("expiration_time")
|
||||
|
||||
t, e := time.Parse("2006-01-02 15:04:05", user.GetString("expiration_time"))
|
||||
fmt.Println(e, "时间创建失败")
|
||||
if t.Unix() >= time.Now().Unix() {
|
||||
tp = "续订"
|
||||
data["expiration_time"] = t.Add(365 * 24 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if user.GetCeilInt("provider_id") != 0 {
|
||||
data["provider_id"] = user.GetCeilInt("provider_id")
|
||||
data["amount"] = 36000
|
||||
//tp=tp
|
||||
}
|
||||
//data["amount"] = 1
|
||||
|
||||
if user.GetCeilInt("salesman_id") != 0 {
|
||||
data["salesman_id"] = user.GetCeilInt("salesman_id")
|
||||
}
|
||||
data["name"] = companyName + tp + "1年VIP会员"
|
||||
|
||||
jsParams, e := wechat.WxPay.GetJsOrder(data.GetCeilInt64("amount"), that.Config.GetString("wechatAppID"), wc.GetString("openid"), data.GetString("name"), data.GetString("sn"), that.Config.GetString("wechatAppNotifyUrl"))
|
||||
if e != nil {
|
||||
fmt.Println(e)
|
||||
that.Display(4, e)
|
||||
return
|
||||
}
|
||||
re := that.Db.Insert("vip_order", data)
|
||||
fmt.Println(re)
|
||||
that.Display(0, jsParams)
|
||||
},
|
||||
"callback": func(that *Context) {
|
||||
data, e := wechat.WxPay.CallbackJsOrder(that.Req)
|
||||
if e != nil {
|
||||
fmt.Println(e)
|
||||
//that.Display(4,e)
|
||||
|
||||
fmt.Println("返回数据错误", e)
|
||||
return
|
||||
}
|
||||
|
||||
sn := data.OutTradeNo
|
||||
amount := int64(data.Amount.Total)
|
||||
state := data.TradeState
|
||||
//state:="SUCCESS"
|
||||
//data := Map{"ces": "das"}
|
||||
//sn := that.Req.FormValue("sn")
|
||||
//amount := ObjToCeilInt64(that.Req.FormValue("amount"))
|
||||
|
||||
if state != "SUCCESS" {
|
||||
|
||||
fmt.Println("购买返回失败", data)
|
||||
return
|
||||
}
|
||||
|
||||
vipOrder := that.Db.Get("vip_order", "*", Map{"sn": sn})
|
||||
|
||||
if vipOrder == nil {
|
||||
|
||||
fmt.Println("找不到订单", vipOrder, data)
|
||||
return
|
||||
}
|
||||
user := that.Db.Get("user", "*", Map{"id": vipOrder.GetCeilInt("user_id")})
|
||||
if user == nil {
|
||||
|
||||
fmt.Println("找不到用户", vipOrder, data)
|
||||
return
|
||||
}
|
||||
if vipOrder.GetCeilInt64("amount") != amount {
|
||||
|
||||
fmt.Println("金额不符", user, vipOrder, amount, data)
|
||||
return
|
||||
}
|
||||
|
||||
that.Db.Update("vip_order", Map{"status": 1}, Map{"id": vipOrder.GetCeilInt("id")})
|
||||
|
||||
idata := Map{"expiration_time": time.Now().Add(365 * 24 * time.Hour).Format("2006-01-02 15:04:05")}
|
||||
if user.GetString("expiration_time") != "" {
|
||||
|
||||
t, e := time.Parse("2006-01-02 15:04:05", user.GetString("expiration_time"))
|
||||
fmt.Println(e, "时间创建失败")
|
||||
if t.Unix() >= time.Now().Unix() {
|
||||
idata["expiration_time"] = t.Add(365 * 24 * time.Hour).Format("2006-01-02 15:04:05")
|
||||
}
|
||||
}
|
||||
|
||||
re := that.Db.Update("user", idata, Map{"id": user.GetCeilInt("id")})
|
||||
if re == 0 {
|
||||
fmt.Println("购买失败", user, vipOrder, re, data)
|
||||
|
||||
return
|
||||
}
|
||||
fmt.Println("成功购买", user, vipOrder, re, data)
|
||||
|
||||
//购买成功后赠送10张券
|
||||
//user_id := that.Session("user_id").Data
|
||||
data2 := Map{
|
||||
"user_id": that.Session("user_id").Data,
|
||||
"coupon_id": 1,
|
||||
"code_no": "SN" + time.Now().Format("20060102150405") + getSn(),
|
||||
"effective_start_time[#]": "NOW()",
|
||||
"effective_end_time": time.Now().AddDate(0, 6, 0).Format("2006-01-02 15:04:05"),
|
||||
"source_type": 1,
|
||||
"status": 0,
|
||||
"admin_id": user.GetCeilInt("admin_id"),
|
||||
"create_time[#]": "NOW()",
|
||||
}
|
||||
for n := 0; n < 5; n++ {
|
||||
that.Db.Insert("coupon_user", data2)
|
||||
}
|
||||
data2["effective_end_time"] = time.Now().AddDate(1, 0, 0).Format("2006-01-02 15:04:05")
|
||||
for n := 0; n < 5; n++ {
|
||||
that.Db.Insert("coupon_user", data2)
|
||||
}
|
||||
return
|
||||
|
||||
},
|
||||
"export": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
buy_date := ObjToStr(that.Req.FormValue("buy_date"))
|
||||
if buy_date == "" {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
//data := that.Db.Query("SELECT vo.sn 订单号, vo.`name` 订单名, vo.user_id 购买用户ID,usr.`name` 购买用户名, usr.phone 购买用户电话, cp.id 企业ID, cp.`name` 企业名,\nvo.expiration_time 过期时间, vo.old_expiration_time 订购前到期时间, vo.amount `订单金额_单位(分)`,\nvo.salesman_id 业务员ID,sm.`name` 业务员名, sm.phone 业务员电话, pv.`name` 服务商名 \nFROM vip_order vo\nLEFT JOIN salesman sm ON sm.id = vo.salesman_id\nLEFT JOIN provider pv ON pv.id = vo.provider_id\nLEFT JOIN `user` usr ON usr.id = vo.user_id\nLEFT JOIN company cp ON cp.id = vo.company_id\nWHERE vo.`status` = 1 AND vo.create_time >= '" + buy_date + "' \nORDER BY vo.create_time")
|
||||
//data := that.Db.Query("SELECT vo.sn 订单号, vo.`name` 订单名, vo.user_id 购买用户ID,usr.`name` 购买用户名, usr.phone 购买用户电话, cp.id 企业ID, cp.`name` 企业名,\nvo.expiration_time 过期时间, vo.old_expiration_time 订购前到期时间, vo.amount `订单金额_单位(分)`,\nvo.salesman_id 业务员ID,sm.`name` 业务员名, sm.phone 业务员电话, pv.`name` 服务商名 \nFROM vip_order vo\n" +
|
||||
// "LEFT JOIN salesman sm ON sm.id = vo.salesman_id\nLEFT JOIN provider pv ON pv.id = vo.provider_id\nLEFT JOIN `user` usr" +
|
||||
// " ON usr.id = vo.user_id\nLEFT JOIN company cp ON cp.id = vo.company_id\nWHERE" +
|
||||
// " vo.`status` = 1 AND vo.create_time >= ? \nORDER BY vo.create_time",buy_date)
|
||||
|
||||
data := that.Db.Select("vip_order", Map{"[>]salesman": "salesman.id=vip_order.salesman_id",
|
||||
"[>]provider": "provider.id = vip_order.provider_id",
|
||||
"[>]user": "user.id = vip_order.user_id",
|
||||
"[>]company": "company.id = vip_order.company_id",
|
||||
}, "vip_order.sn 订单号, vip_order.`name` 订单名, vip_order.user_id 购买用户ID,user.`name` 购买用户名, user.phone 购买用户电话, company.id 企业ID, company.`name` 企业名,\nvip_order.expiration_time 过期时间, vip_order.amount `订单金额_单位(分)`,\nvip_order.salesman_id 业务员ID,salesman.`name` 业务员名, salesman.phone 业务员电话, provider.`name` 服务商名",
|
||||
Map{"AND": Map{"vip_order.status": 1, "vip_order.create_time[>=]": buy_date}, "ORDER": "vip_order.create_time DESC"})
|
||||
|
||||
if len(data) == 0 {
|
||||
that.Display(0, "今日没有vip购买信息数据")
|
||||
return
|
||||
}
|
||||
|
||||
var titleList []string
|
||||
if data != nil {
|
||||
m := data[0]
|
||||
for k, _ := range m {
|
||||
titleList = append(titleList, k)
|
||||
}
|
||||
}
|
||||
|
||||
var dataList []Map
|
||||
for _, v := range data {
|
||||
dataList = append(dataList, v)
|
||||
}
|
||||
|
||||
//打印最后一次sql语句
|
||||
//that.Db.LastQuery
|
||||
//请求的数据
|
||||
//that.Db.LastData
|
||||
//that.Db.LastErr
|
||||
//appIns.Db.Select("company",common.Map{"[<>]user":"company.id=user.company_id"},"company.id as id",common.Map{"AND":common.Map{"id[!]":nil},"ORDER":"id DESC"})
|
||||
//appIns.Db.Query("select * from user where id = ? and name = ?",common.Slice{1,"nn"})
|
||||
|
||||
//titleList:= []string{"aaaa", "vvvvv", "dddd", "eeeee", "gfgggg"}
|
||||
DataToExcel(that.Resp, that.Req, titleList, dataList, buy_date+"vip购买信息分析数据")
|
||||
},
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"golang.org/x/net/websocket"
|
||||
"time"
|
||||
)
|
||||
|
||||
type WSClient struct {
|
||||
ID string
|
||||
*websocket.Conn
|
||||
time.Time
|
||||
DeadTime time.Time
|
||||
IsDead bool
|
||||
}
|
||||
|
||||
//websocket链接池
|
||||
var WsUserMap = map[string][]*WSClient{}
|
||||
var WSMasterID = ""
|
||||
|
||||
func WsSendMsg(ws *WSClient, data Map) bool {
|
||||
if WsUserMap[ws.ID] == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, v := range WsUserMap[ws.ID] {
|
||||
if v.IsDead || v == ws {
|
||||
//WsUserMap[ws.ID]=WsUserMap[ws.ID][:k]
|
||||
continue
|
||||
}
|
||||
|
||||
str := data.ToJsonString()
|
||||
v.Conn.Write([]byte(str))
|
||||
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
var WebsocketCtr = Ctr{
|
||||
"conn": func(this *Context) {
|
||||
id := this.SessionId
|
||||
if WsUserMap[id] == nil {
|
||||
WsUserMap[id] = []*WSClient{}
|
||||
}
|
||||
hdler := websocket.Handler(func(ws *websocket.Conn) {
|
||||
|
||||
client := &WSClient{ID: id, Conn: ws, Time: time.Now(), DeadTime: time.Now(), IsDead: false}
|
||||
|
||||
WsUserMap[id] = append(WsUserMap[id], client)
|
||||
var message string
|
||||
for true {
|
||||
err := websocket.Message.Receive(ws, &message)
|
||||
if err != nil {
|
||||
client.DeadTime = time.Now()
|
||||
client.IsDead = true
|
||||
return
|
||||
}
|
||||
|
||||
data := Map{}
|
||||
data.JsonToMap(message)
|
||||
WsSendMsg(client, data)
|
||||
//switch data.GetString("type") {
|
||||
//
|
||||
//}
|
||||
|
||||
}
|
||||
})
|
||||
hdler.ServeHTTP(this.Resp, this.Req)
|
||||
},
|
||||
}
|
||||
@@ -1,287 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"code.hoteas.com/golang/hotime/dri/wechat"
|
||||
"time"
|
||||
)
|
||||
|
||||
var Wechath5 = Ctr{
|
||||
|
||||
//微信注册,0已经完整的注册了,1还没有注册
|
||||
"code": func(that *Context) {
|
||||
|
||||
if that.Req.FormValue("code") == "" {
|
||||
that.Display(3, "参数不足")
|
||||
return
|
||||
}
|
||||
|
||||
appid, resToken, userInfo, err := wechat.H5Program.GetUserInfo(that.Req.FormValue("code"))
|
||||
|
||||
if err != nil {
|
||||
that.Display(4, err)
|
||||
return
|
||||
}
|
||||
//此次获取的微信信息
|
||||
wechatInfo := Map{
|
||||
"openid": userInfo.OpenID,
|
||||
"acttoken": resToken.AccessToken,
|
||||
"retoken": resToken.RefreshToken,
|
||||
"appid": appid,
|
||||
"unionid": userInfo.Unionid,
|
||||
"nickname": FilterEmoji(userInfo.Nickname),
|
||||
"avatar": userInfo.HeadImgURL,
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
"type": 1,
|
||||
}
|
||||
|
||||
userId := 0
|
||||
|
||||
//这个defer放到上面,防止出现用户第一次登陆的时候出现不返回company和salesman的情况
|
||||
//如果有则直接返回用户信息到微信小程序里
|
||||
defer func() {
|
||||
if userId != 0 {
|
||||
user := that.Db.Get("user", "*", Map{"id": userId})
|
||||
if user == nil {
|
||||
that.Display(4, "获取个人信息失败")
|
||||
return
|
||||
}
|
||||
delete(user, "password")
|
||||
company := that.Db.Get("company", "id,name", Map{"id": user.GetCeilInt("company_id")})
|
||||
|
||||
//消除company没有创建的影响
|
||||
if company == nil {
|
||||
companyId := that.Db.Insert("company", Map{
|
||||
"user_id": user["id"],
|
||||
"provider_id": user["provider_id"],
|
||||
"salesman_id": user["salesman_id"],
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
})
|
||||
user["company_id"] = companyId
|
||||
that.Db.Update("user", Map{"company_id": companyId}, Map{"id": user.GetCeilInt("id")})
|
||||
company = that.Db.Get("company", "*", Map{"id": user.GetCeilInt("company_id")})
|
||||
}
|
||||
salesman := that.Db.Get("salesman", "id,name", Map{"id": user.GetCeilInt("salesman_id")})
|
||||
provider := that.Db.Get("provider", "id,name", Map{"id": user.GetCeilInt("provider_id")})
|
||||
|
||||
user["company"] = company
|
||||
user["salesman"] = salesman
|
||||
user["provider"] = provider
|
||||
|
||||
that.Display(0, user)
|
||||
}
|
||||
}()
|
||||
|
||||
defer func() {
|
||||
|
||||
//有sn就关联业务员
|
||||
parentId := ObjToInt(that.Req.FormValue("parent_id"))
|
||||
if parentId == 0 {
|
||||
return
|
||||
}
|
||||
if userId == 0 || userId == parentId {
|
||||
return
|
||||
}
|
||||
puser := that.Db.Get("user", "`index`,id", Map{"id": parentId})
|
||||
if puser == nil {
|
||||
return
|
||||
}
|
||||
user := that.Db.Get("user", "parent_id", Map{"id": userId})
|
||||
if user.GetCeilInt("parent_id") != 0 {
|
||||
return
|
||||
}
|
||||
index1 := puser.GetString("index")
|
||||
if index1 == "," {
|
||||
index1 = index1 + ObjToStr(parentId) + ","
|
||||
}
|
||||
|
||||
//2022/5/11 zpw 添加字段:用户关联parenid的时间 (join_parent_time)
|
||||
that.Db.Update("user", Map{"parent_id": parentId, "index": index1 + ObjToStr(userId) + ",", "join_parent_time[#]": "NOW()"}, Map{"id": userId})
|
||||
//在这里做判断 能否通过分享领券
|
||||
//如果通过邀请获得的券超过了三张则不再赠送
|
||||
//赠送一张券
|
||||
data := Map{
|
||||
"user_id": parentId,
|
||||
"coupon_id": 1,
|
||||
"code_no": "SN" + time.Now().Format("20060102150405") + getSn(),
|
||||
"effective_start_time[#]": "NOW()",
|
||||
"effective_end_time": time.Now().AddDate(0, 6, 0).Format("2006-01-02 15:04:05"),
|
||||
"source_type": 3,
|
||||
"status": 0,
|
||||
"admin_id": user.GetCeilInt("admin_id"),
|
||||
"create_time[#]": "NOW()",
|
||||
}
|
||||
//先判断是否领取过 source_type=3 是通过拉新赠送的券
|
||||
couponCount := that.Db.Count("coupon_user", Map{"AND": Map{"user_id": parentId, "source_type": 3}})
|
||||
if couponCount < 3 {
|
||||
that.Db.Insert("coupon_user", data)
|
||||
}
|
||||
|
||||
}()
|
||||
//最后验证服务商是否绑定
|
||||
defer func() {
|
||||
//有sn就关联业务员
|
||||
sn := that.Req.FormValue("sn")
|
||||
if sn == "" {
|
||||
return
|
||||
}
|
||||
if userId == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
salesman := that.Db.Get("salesman", "*", Map{"sn": sn})
|
||||
if salesman.GetCeilInt("id") == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
user := that.Db.Get("user", "*", Map{"id": userId})
|
||||
if user == nil {
|
||||
return
|
||||
}
|
||||
|
||||
//用户都有企服人员关联
|
||||
if user.GetCeilInt("salesman_id") != 0 {
|
||||
|
||||
return
|
||||
}
|
||||
//用户没有企服商id
|
||||
//2022/5/11 zpw 添加字段:用户关联企服商业务人员的时间 (join_salesman_time)
|
||||
that.Db.Update("user", Map{"salesman_id": salesman.GetCeilInt64("id"), "provider_id": salesman.GetCeilInt64("provider_id"), "join_salesman_time[#]": "NOW()"}, Map{"id": user.GetCeilInt64("id")})
|
||||
if user.GetCeilInt("company_id") == 0 {
|
||||
return
|
||||
}
|
||||
//绑定企业
|
||||
that.Db.Update("company", Map{"salesman_id": salesman.GetCeilInt64("id"), "provider_id": salesman.GetCeilInt64("provider_id")}, Map{"id": user.GetCeilInt64("company_id")})
|
||||
|
||||
}()
|
||||
|
||||
wechat := that.Db.Get("wechat", "*", Map{"AND": Map{"openid": userInfo.OpenID, "del_flag": 0}})
|
||||
|
||||
if wechat != nil {
|
||||
//有用户直接返回
|
||||
if wechat.GetCeilInt("user_id") != 0 {
|
||||
|
||||
that.Db.Update("user", Map{"login_time[#]": "now()"}, Map{"id": wechat.GetCeilInt("user_id")})
|
||||
that.Session("wechat_id", wechat.GetCeilInt("id"))
|
||||
that.Session("user_id", wechat.GetCeilInt("user_id"))
|
||||
|
||||
userId = wechat.GetCeilInt("user_id")
|
||||
//that.Display(0, "登录成功")
|
||||
return
|
||||
}
|
||||
//没有用户继续查询数据库看是否有其他unionid
|
||||
wechat1 := that.Db.Get("wechat", "*", Map{"AND": Map{"unionid": userInfo.Unionid, "openid[!]": userInfo.OpenID, "user_id[>]": 0, "del_flag": 0}})
|
||||
|
||||
//其他表有该数据,则更新当前表数据信息
|
||||
if wechat1 != nil {
|
||||
|
||||
wechatInfo["user_id"] = wechat1.GetCeilInt("user_id")
|
||||
that.Db.Update("wechat", wechatInfo, Map{"id": wechat.GetCeilInt("id")})
|
||||
|
||||
that.Db.Update("user", Map{"login_time[#]": "now()"}, Map{"id": wechat1.GetCeilInt("user_id")})
|
||||
that.Session("wechat_id", wechat.GetCeilInt("id"))
|
||||
that.Session("user_id", wechatInfo.GetCeilInt("user_id"))
|
||||
|
||||
userId = wechatInfo.GetCeilInt("user_id")
|
||||
//that.Display(0, "登录成功")
|
||||
return
|
||||
}
|
||||
|
||||
//其他表也没有当前信息,则生成user表,并更新当前用户,一般不会走到这里来
|
||||
user := Map{
|
||||
"nickname": wechatInfo.GetString("nickname"),
|
||||
"avatar": wechatInfo.GetString("avatar"),
|
||||
"index": ",",
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"login_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
}
|
||||
user["id"] = that.Db.Insert("user", user)
|
||||
//创建企业
|
||||
user["company_id"] = that.Db.Insert("company", Map{
|
||||
"user_id": user["id"],
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
})
|
||||
that.Db.Update("user", Map{"company_id": user["company_id"]}, Map{"id": user["id"]})
|
||||
|
||||
wechatInfo["user_id"] = user.GetCeilInt("id")
|
||||
|
||||
that.Db.Update("wechat", wechatInfo, Map{"id": wechat.GetCeilInt("id")})
|
||||
|
||||
that.Session("wechat_id", wechat.GetCeilInt("id"))
|
||||
that.Session("user_id", wechatInfo.GetCeilInt("user_id"))
|
||||
|
||||
userId = wechatInfo.GetCeilInt("user_id")
|
||||
//that.Display(0, "登录成功")
|
||||
return
|
||||
}
|
||||
user := Map{
|
||||
"nickname": wechatInfo.GetString("nickname"),
|
||||
"avatar": wechatInfo.GetString("avatar"),
|
||||
"index": ",",
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"login_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
}
|
||||
user["id"] = that.Db.Insert("user", user)
|
||||
user["company_id"] = that.Db.Insert("company", Map{
|
||||
"user_id": user["id"],
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
})
|
||||
|
||||
that.Db.Update("user", Map{"company_id": user["company_id"]}, Map{"id": user["id"]})
|
||||
|
||||
wechatInfo["user_id"] = user.GetCeilInt("id")
|
||||
|
||||
wechatInfo["id"] = that.Db.Insert("wechat", wechatInfo)
|
||||
|
||||
if wechatInfo.GetCeilInt("id") == 0 {
|
||||
that.Display(4, "创建用户失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Session("wechat_id", wechatInfo.GetCeilInt("id"))
|
||||
that.Session("user_id", wechatInfo.GetCeilInt("user_id"))
|
||||
|
||||
userId = wechatInfo.GetCeilInt("user_id")
|
||||
//that.Display(0, "登录成功")
|
||||
|
||||
},
|
||||
//网页签名
|
||||
"sign": func(that *Context) {
|
||||
|
||||
signUrl := that.Req.FormValue("url")
|
||||
if signUrl == "" {
|
||||
that.Display(3, "参数不足")
|
||||
return
|
||||
}
|
||||
|
||||
cfg1, e := wechat.H5Program.GetSignUrl(signUrl)
|
||||
|
||||
if e != nil {
|
||||
that.Display(4, e)
|
||||
return
|
||||
}
|
||||
|
||||
sign := Map{
|
||||
"appId": cfg1.AppID,
|
||||
"timestamp": cfg1.Timestamp,
|
||||
"nonceStr": cfg1.NonceStr,
|
||||
"signature": cfg1.Signature,
|
||||
}
|
||||
|
||||
that.Display(0, sign)
|
||||
|
||||
},
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"code.hoteas.com/golang/hotime/dri/wechat"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var WechatMini = Ctr{
|
||||
"getphone": func(that *Context) {
|
||||
|
||||
//sessionKey := that.Req.FormValue("sessionkey")
|
||||
|
||||
if that.Session("wechat_id").Data == nil {
|
||||
that.Display(2, "请先登录")
|
||||
return
|
||||
}
|
||||
|
||||
encryptedData := that.Req.FormValue("encryptedData")
|
||||
iv := that.Req.FormValue("iv")
|
||||
|
||||
if encryptedData == "" || iv == "" {
|
||||
that.Display(3, "参数不足")
|
||||
return
|
||||
}
|
||||
|
||||
wechatIns := that.Db.Get("wechat", "sessionkey", Map{"id": that.Session("wechat_id").ToCeilInt()})
|
||||
_, re, e := wechat.MiniProgram.GetPhoneNumber(wechatIns.GetString("sessionkey"), encryptedData, iv)
|
||||
|
||||
if e != nil {
|
||||
that.Display(4, e)
|
||||
return
|
||||
}
|
||||
//临时存储用于校验
|
||||
that.Session("wechat_phone", re.PhoneNumber)
|
||||
that.Display(0, re.PhoneNumber)
|
||||
|
||||
},
|
||||
//检查是否已经有用户登录了,如果有直接登录,如果没有则查询unionid,有则直接返回用户信息,没有则返回null
|
||||
"code": func(that *Context) {
|
||||
|
||||
code := that.Req.FormValue("code")
|
||||
if code == "" {
|
||||
that.Display(3, "缺少code")
|
||||
return
|
||||
}
|
||||
|
||||
appid, re, e := wechat.MiniProgram.GetBaseUserInfo(code)
|
||||
fmt.Println(re)
|
||||
if e != nil {
|
||||
that.Display(4, e)
|
||||
return
|
||||
}
|
||||
|
||||
wchat := Map{"openid": re.OpenID,
|
||||
"appid": appid,
|
||||
"sessionkey": re.SessionKey,
|
||||
"unionid": re.UnionID,
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
"type": 2,
|
||||
}
|
||||
|
||||
userId := 0
|
||||
|
||||
//如果有则直接返回用户信息到微信小程序里
|
||||
defer func() {
|
||||
if userId != 0 {
|
||||
user := that.Db.Get("user", "*", Map{"id": userId})
|
||||
company := that.Db.Get("company", "id,name", Map{"id": user.GetCeilInt("company_id")})
|
||||
salesman := that.Db.Get("salesman", "id,name", Map{"id": user.GetCeilInt("salesman_id")})
|
||||
provider := that.Db.Get("provider", "id,name", Map{"id": user.GetCeilInt("provider_id")})
|
||||
if user == nil {
|
||||
that.Display(4, "获取个人信息失败")
|
||||
return
|
||||
}
|
||||
delete(user, "password")
|
||||
user["company"] = company
|
||||
user["salesman"] = salesman
|
||||
user["provider"] = provider
|
||||
that.Display(0, user)
|
||||
}
|
||||
}()
|
||||
|
||||
wechat := that.Db.Get("wechat", "*", Map{"AND": Map{"openid": re.OpenID, "user_id[!]": nil, "del_flag": 0}})
|
||||
//有该用户,则登录成功
|
||||
if wechat != nil {
|
||||
|
||||
that.Session("wechat_id", wechat.GetCeilInt("id"))
|
||||
that.Session("user_id", wechat.GetCeilInt("user_id"))
|
||||
//更新用户信息
|
||||
that.Db.Update("wechat", wchat, Map{"id": wechat.GetCeilInt("id")})
|
||||
//that.Display(0, "登录成功")
|
||||
userId = wechat.GetCeilInt("user_id")
|
||||
return
|
||||
}
|
||||
|
||||
//如果其他人有相关信息,则直接取用
|
||||
wechat = that.Db.Get("wechat", "*", Map{"AND": Map{"unionid": re.UnionID, "user_id[!]": nil, "del_flag": 0}})
|
||||
if wechat != nil {
|
||||
wechat1 := that.Db.Get("wechat", "*", Map{"AND": Map{"openid": re.OpenID, "del_flag": 0}})
|
||||
//有该信息,但没有相关的用户信息,则直接绑定其他的信息上来
|
||||
if wechat1 != nil {
|
||||
|
||||
//更新用户信息
|
||||
that.Db.Update("wechat", wchat, Map{"id": wechat1.GetCeilInt("id")})
|
||||
|
||||
that.Session("wechat_id", wechat1.GetCeilInt("id"))
|
||||
that.Session("user_id", wechat.GetCeilInt("user_id"))
|
||||
//that.Display(0, "登录成功")
|
||||
userId = wechat.GetCeilInt("user_id")
|
||||
return
|
||||
}
|
||||
//没有相关用户信息,则新建wechat并完成登录
|
||||
wchat["user_id"] = wechat["user_id"]
|
||||
wchat["create_time[#]"] = "now()"
|
||||
|
||||
wchat["id"] = that.Db.Insert("wechat", wchat)
|
||||
if wchat.GetCeilInt("id") == 0 {
|
||||
|
||||
that.Display(5, "创建wechat失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Session("wechat_id", wchat.GetCeilInt("id"))
|
||||
that.Session("user_id", wchat.GetCeilInt("user_id"))
|
||||
|
||||
userId = wchat.GetCeilInt("user_id")
|
||||
//that.Display(0, "登录成功")
|
||||
return
|
||||
}
|
||||
|
||||
user := Map{
|
||||
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"login_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
}
|
||||
user["id"] = that.Db.Insert("user", user)
|
||||
|
||||
user["company_id"] = that.Db.Insert("company", Map{
|
||||
"user_id": user["id"],
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
})
|
||||
|
||||
that.Db.Update("user", Map{"company_id": user["company_id"]}, Map{"id": user["id"]})
|
||||
|
||||
wchat["user_id"] = user.GetCeilInt("id")
|
||||
wchat["create_time[#]"] = "now()"
|
||||
|
||||
wchat["id"] = that.Db.Insert("wechat", wchat)
|
||||
if wchat.GetCeilInt("id") == 0 {
|
||||
that.Display(5, "登录失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Session("wechat_id", wchat.GetCeilInt("id"))
|
||||
that.Session("user_id", wchat.GetCeilInt("user_id"))
|
||||
|
||||
userId = wchat.GetCeilInt("user_id")
|
||||
//that.Display(0, nil)
|
||||
},
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
{
|
||||
"aliyunCode": "06c6a07e89dd45c88de040ee1489eef7",
|
||||
"avatarPath": "avatar/2006/01/02/",
|
||||
"cache": {
|
||||
"db": {
|
||||
"db": false,
|
||||
"session": true
|
||||
"session": true,
|
||||
"timeout": 7200
|
||||
},
|
||||
"memory": {
|
||||
"db": true,
|
||||
@@ -15,18 +14,18 @@
|
||||
"codeConfig": [
|
||||
{
|
||||
"config": "config/admin.json",
|
||||
"configDB": "config/adminDB.json",
|
||||
"mode": 0,
|
||||
"name": "",
|
||||
"rule": "config/adminRule.json",
|
||||
"rule": "config/rule.json",
|
||||
"table": "admin"
|
||||
}
|
||||
],
|
||||
"crossDomain": "",
|
||||
"db": {
|
||||
"mysql": {
|
||||
"host": "192.168.2.50",
|
||||
"name": "zct_v2_v2",
|
||||
"password": "kct@2021",
|
||||
"host": "192.168.2.20",
|
||||
"name": "gov_crawler",
|
||||
"password": "fh22y8b882d",
|
||||
"port": "3306",
|
||||
"prefix": "",
|
||||
"user": "root"
|
||||
@@ -41,26 +40,10 @@
|
||||
"2": "访问权限异常",
|
||||
"3": "请求参数异常",
|
||||
"4": "数据处理异常",
|
||||
"5": "数据结果异常",
|
||||
"6": "需要进一步获取个人信息"
|
||||
"5": "数据结果异常"
|
||||
},
|
||||
"imgPath": "img/2006/01/02/",
|
||||
"mode": 2,
|
||||
"port": "8081",
|
||||
"sessionName": "HOTIME",
|
||||
"smsKey": "b0eb4bf0198b9983cffcb85b69fdf4fa",
|
||||
"smsLogin": "【政策通】您的验证码为:{code},请在5分钟内使用,切勿将验证码泄露于他人,如非本人操作请忽略。",
|
||||
"tencentId": "AKIDOgT8cKCQksnY7yKATaYO7j9ORJzSYohP",
|
||||
"tencentKey": "GNXgjdN4czA9ya0FNMApVJzTmsmU0KSN",
|
||||
"tpt": "tpt",
|
||||
"wechatAppID": "wxdcc8d6360661a179",
|
||||
"wechatAppNotifyUrl": "https://zcth5.kct.cn/app/vip_order/callback",
|
||||
"wechatAppSecret": "4d793683ca915264663a9c9a33530c3c",
|
||||
"wechatMiniAppID": "wx1c795e883b5b54c4",
|
||||
"wechatMiniAppSecret": "d2bec12d1fa4d8b5714ccbed1c0671e4",
|
||||
"wechatPayMApiV3Key": "dh33tyagd1623623GDYGGDhe1d9dh171",
|
||||
"wechatPayMCHID": "1624888906",
|
||||
"wechatPayPrivateKey": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC1vs3i/4sozxsK\noiS2S95rl+csLXQDugg23bcAVzXr7ZeTM/h81sCwraQDMnAJ/V3n7LxFAZeaFwLb\nyrkQ3lv4IEtWVgjVUkjkhvKGWcAp16Q/grOpxWmmn+VlW5ZGwQQ4DL4sC6BeEyxu\nUdtZ7UVc9lqsQX01R0oiegItJGPMMXNgeLFDEeoAwyIQcL0VG2bND7qrEVeQkLTj\nFm9ZkSb0LySPkSgqxMlSpiX1MS+wWWIHpq91CvdVHNowaGFA7ajU3RztbFAuxdpl\ng9RIocbrY1QwGXouQTEOUI2KZaES9rAa2lD6oWom4mRYiQ1oNO12XlUTcKsr84P5\nTq50dOYFAgMBAAECggEAQUns/mncnOlhhn1fANnaaf5kvlsJvTj8MHGPhyDNLxbo\nB6p4zqf7Cr0mGTvqQbxyGpnRvFxpEKLJlRmLSAMJOOapCbfYboGjy+yqfRcK0D02\nNNaIIinX3VK9fp7bKkm2cUgqnPoEPydWI79mNDTnYRDi29Se3R/iAuafl4XmD/js\nOKWG5tlXEatZ+gDbhnug4hp3xEGm4pbTS1HedV7HgYiKpxAT9uc/YmiHelZUUqlG\nwa1Nda2J88pzCSZX6TsRyY9UF/sjorxSNZGfj+5waeYMccj0Cx4uEQYgBv5tm+I+\nFTRgo/riM5gT9oRTnuNuzUrNwUNLyUsldvdQdlheNQKBgQDqwhrW52q3xClFLXR4\nHu9cTPt/p96MYE+xBllO/M9VFcG/hT++9R9l26+o26Lu+iIF5euDQiYSyURniGim\nWfV0I2q8HufhPLJBamvxRPI0V8LHwbY7c6HKnRR3eDAWAVYIcmsV4RLS67bsgtnr\nCgaFUDHXnpPKjxp1b4M5K3GqxwKBgQDGMLgAQn0a3nZwquPD4D+6tjy5xTxDX4Op\nULHBQheX0lBAR9Kcurzy4ca+T5xsyHd6SPwQxobRPei/3TBmc18J1T3nxJkTbEEP\nqy8k7MOWW2es3ou4CRL5lVKPx4YDWb5iT7X3Ue55JjPFAoj6FBOHxdvRQnDYsLFy\nSuSHPc280wKBgQCqfvCZNZcnAbtrd3jIKMd0hKB/dP7HesdF7TN9j1RRGi0NmIvU\ndxgnlOa9v05VO6rsF7D1MlyOdkhM3SAL+PewMmy5VcTYq4lWwyDEKGuzoi1fgIuG\nIBPYID8WCV77DFtcZSTqzf0q3HCM0vfLoQtdVQHt9Ein60ivE579LVUvTwKBgFid\nefgrwnJcG8serb5sKzKZvyc1CE/7igwPl5sYqSHqGJXVR1dqq4dR6iI3yHJfZASa\nU5JQogE21DXNeZGlbk4gOZDCt8sWcTTHTsoMzxsQfZeu3fwImqJb4NGG3eXrn5On\nnm4aBS3IJgelrYdbqKvhjPrQ4VISFxVKZUoPGUmfAoGARZbtbyl3s8cAExWe9dK6\nyWdkA3M2wR4n623W13rTQDc3D7p/hmlgB2x8it88m+580326G4qgwdUbG93EW1WQ\nahbkkcmdxzHgPVJdsyx22fR0TkeT1gjMpoSh4k3HOsbZE4EvlI459yE9fTSLBq2A\nFzGjYRpBTlRyrsSEhyVg4G0=\n-----END PRIVATE KEY-----",
|
||||
"wechatPaySerialNo": "7A92D2D26D212D6BF934BDB10D547274807C3DDB",
|
||||
"wxFilePath": "wxfile/2006/01/02/"
|
||||
"tpt": "tpt"
|
||||
}
|
||||
@@ -24,6 +24,7 @@
|
||||
"注释:配置即启用,非必须,默认无",
|
||||
{
|
||||
"config": "默认config/app.json,必须,接口描述配置文件",
|
||||
"configDB": "默认无,非必须,有则每次将数据库数据生成到此目录用于配置读写,无则不生成",
|
||||
"mode": "默认0,非必须,0为内嵌代码模式,1为生成代码模式",
|
||||
"name": "默认无,非必须,有则生成代码到此目录,无则采用缺省模式使用表名,如设置为:admin,将在admin目录生成包名为admin的代码",
|
||||
"rule": "默认config/rule.json,非必须,有则按改规则生成接口,无则按系统内嵌方式生成",
|
||||
|
||||
Binary file not shown.
+2
-73
@@ -2,88 +2,17 @@ package main
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
"code.hoteas.com/golang/hotime/dri/aliyun"
|
||||
"code.hoteas.com/golang/hotime/dri/ddsms"
|
||||
"code.hoteas.com/golang/hotime/dri/tencent"
|
||||
"code.hoteas.com/golang/hotime/dri/wechat"
|
||||
"code.hoteas.com/golang/hotime/example/app"
|
||||
"code.hoteas.com/golang/hotime/example/provider"
|
||||
//. "code.hoteas.com/golang/hotime/common"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
//
|
||||
func main() {
|
||||
date, _ := time.Parse("2006-01-02 15:04", time.Now().Format("2006-01-02")+" 14:00")
|
||||
fmt.Println(date, date.Unix())
|
||||
//fmt.Println("开始测试")
|
||||
//t:=common.Map{"t":1652425167}
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//t["t"]=1652425167123
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//t["t"]=1652425167123456
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//t["t"]=1652425167123456789
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//fmt.Println("开始测试2")
|
||||
//t["t"]="2006-01-02 15:04:05"
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//t["t"]="2006-01-02 15"
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//t["t"]="2006-01-02"
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//t["t"]="2006-01"
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//t["t"]="2006-01"
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//t["t"]="2006"
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
//
|
||||
//t["t"]="06"
|
||||
//fmt.Println(t.GetTime("t"))
|
||||
|
||||
//fmt.Println("0123456"[1:7])
|
||||
appIns := Init("config/config.json")
|
||||
|
||||
aliyun.Company.Init(appIns.Config.GetString("aliyunCode"))
|
||||
|
||||
//初始化短信配置
|
||||
ddsms.DDY.Init(appIns.Config.GetString("smsKey"))
|
||||
//初始化公众号配置
|
||||
wechat.H5Program.Init(appIns.Config.GetString("wechatAppID"), appIns.Config.GetString("wechatAppSecret"))
|
||||
//初始化小程序配置
|
||||
wechat.MiniProgram.Init(appIns.Config.GetString("wechatMiniAppID"), appIns.Config.GetString("wechatMiniAppSecret"))
|
||||
//初始化小程序及公众号支付配置
|
||||
wechat.WxPay.Init(appIns.Config.GetString("wechatPayMCHID"),
|
||||
appIns.Config.GetString("wechatPaySerialNo"),
|
||||
appIns.Config.GetString("wechatPayMApiV3Key"),
|
||||
appIns.Config.GetString("wechatPayPrivateKey"))
|
||||
tencent.Tencent.Init(appIns.Config.GetString("tencentId"), appIns.Config.GetString("tencentKey"))
|
||||
|
||||
//用户侧访问前设置
|
||||
appIns.SetConnectListener(func(that *Context) (isFinished bool) {
|
||||
//发送短信校验
|
||||
//that.RespFunc = func() {
|
||||
// go func(Form url.Values, RespData common.Map) {
|
||||
// fmt.Println(Form)
|
||||
// fmt.Println(RespData)
|
||||
// }(that.Req.Form, that.RespData)
|
||||
//
|
||||
//}
|
||||
|
||||
return isFinished
|
||||
})
|
||||
|
||||
//appIns.SetConnectListener(func(that *Context) (isFinished bool) {
|
||||
//
|
||||
// return isFinished
|
||||
//})
|
||||
//appIns.Db.Action(func(db db.HoTimeDB) (isSuccess bool) {
|
||||
// return isSuccess
|
||||
//})
|
||||
appIns.Run(Router{
|
||||
"provider": provider.Project,
|
||||
"app": app.Project,
|
||||
})
|
||||
appIns.Run(Router{"app": app.AppProj})
|
||||
|
||||
}
|
||||
|
||||
@@ -1,144 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"code.hoteas.com/golang/hotime/dri/aliyun"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
var CompanyCtr = Ctr{
|
||||
|
||||
"search": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords == "" {
|
||||
keywords = that.Req.FormValue("company_name")
|
||||
}
|
||||
if keywords == "" {
|
||||
keywords = that.Req.FormValue("name")
|
||||
}
|
||||
|
||||
if len(keywords) < 2 {
|
||||
that.Display(0, Slice{})
|
||||
return
|
||||
}
|
||||
|
||||
res, err := aliyun.Company.GetCompanyList(keywords)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
that.Display(0, Slice{})
|
||||
return
|
||||
}
|
||||
if res.GetCeilInt64("status") != 200 {
|
||||
fmt.Println(err)
|
||||
that.Display(0, Slice{})
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, res.GetMap("data").GetSlice("list"))
|
||||
},
|
||||
"search_info": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
name := that.Req.FormValue("name")
|
||||
|
||||
if len(name) < 2 {
|
||||
that.Display(3, "找不到企业")
|
||||
return
|
||||
}
|
||||
|
||||
res, err := aliyun.Company.GetCompanyBaseInfo(name)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
that.Display(4, "查询失败")
|
||||
return
|
||||
}
|
||||
if res.GetBool("status") != true {
|
||||
fmt.Println(err)
|
||||
that.Display(4, "查询失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, res.GetMap("data"))
|
||||
},
|
||||
|
||||
"info": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("company", "*", Map{"id": id})
|
||||
if res == nil {
|
||||
that.Display(4, "找不到企业")
|
||||
return
|
||||
}
|
||||
//先不做限制
|
||||
//if res.GetCeilInt("salesman_id")!=that.Session("salesman_id").ToCeilInt(){
|
||||
// that.Display(4,"不是你的企业")
|
||||
// return
|
||||
//}
|
||||
|
||||
res["technology_center_flag"] = strToArray(res.GetString("technology_center_flag"))
|
||||
res["engineering_center_flag"] = strToArray(res.GetString("engineering_center_flag"))
|
||||
res["engineering_laboratory_flag"] = strToArray(res.GetString("engineering_laboratory_flag"))
|
||||
res["key_laboratory_flag"] = strToArray(res.GetString("key_laboratory_flag"))
|
||||
res["industrial_design_center_flag"] = strToArray(res.GetString("industrial_design_center_flag"))
|
||||
res["high_level_talents_flag1"] = strToArray(res.GetString("high_level_talents_flag1"))
|
||||
res["tags"] = strToArray(res.GetString("tags"))
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
"edit": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
company := that.Db.Get("company", "*", Map{"id": id})
|
||||
delete(company, "id")
|
||||
delete(company, "salesman_id")
|
||||
delete(company, "provider_id")
|
||||
delete(company, "user_id")
|
||||
delete(company, "del_flag")
|
||||
delete(company, "state")
|
||||
delete(company, "create_time")
|
||||
delete(company, "modify_time")
|
||||
data := Map{}
|
||||
for k, _ := range company {
|
||||
if that.Req.Form[k] != nil {
|
||||
if k == "tags" || k == "high_level_talents_flag1" || k == "technology_center_flag" || k == "engineering_center_flag" || k == "engineering_laboratory_flag" || k == "key_laboratory_flag" || k == "industrial_design_center_flag" {
|
||||
data[k] = arrayToStr(ObjToSlice(that.Req.Form[k]))
|
||||
} else {
|
||||
data[k] = that.Req.FormValue(k)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
that.Db.Update("company", data, Map{"id": id})
|
||||
|
||||
that.Display(0, "更新成功")
|
||||
|
||||
},
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var DeclareCtr = Ctr{
|
||||
|
||||
"info": func(that *Context) {
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("declare", "*", Map{"id": id})
|
||||
|
||||
if res == nil {
|
||||
that.Display(4, "找不到通知公告")
|
||||
return
|
||||
}
|
||||
res["click_num"] = res.GetCeilInt64("click_num") + res.GetCeilInt64("click_num_base") + 1
|
||||
delete(res, "click_num_base")
|
||||
|
||||
res["favorite_num"] = res.GetCeilInt64("favorite_num") + res.GetCeilInt64("favorite_num_base")
|
||||
delete(res, "favorite_num_base")
|
||||
|
||||
article := that.Db.Get("article", "*", Map{"id": res.GetCeilInt64("article_id")})
|
||||
if article != nil {
|
||||
article["click_num"] = article.GetCeilInt64("click_num") + article.GetCeilInt64("click_num_base") + 1
|
||||
delete(article, "click_num_base")
|
||||
|
||||
article["favorite_num"] = article.GetCeilInt64("favorite_num") + article.GetCeilInt64("favorite_num_base")
|
||||
delete(article, "favorite_num_base")
|
||||
}
|
||||
|
||||
res["article"] = article
|
||||
|
||||
//浏览量加1
|
||||
that.Db.Update("declare", Map{"click_num[#]": "click_num+1"}, Map{"id": id})
|
||||
//浏览量加1
|
||||
that.Db.Update("article", Map{"click_num[#]": "click_num+1"}, Map{"id": res.GetCeilInt64("article_id")})
|
||||
|
||||
//查询是否已关注
|
||||
if that.Session("user_id").Data != nil {
|
||||
favorite := that.Db.Get("favorite", "user_id,declare_id", Map{"AND": Map{"declare_id": id, "user_id": that.Session("user_id").ToCeilInt(), "del_flag": 0}})
|
||||
res["favorite"] = favorite
|
||||
}
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "declare_id[!]": nil}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["release_date[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["release_date[<=]"] = finishTime
|
||||
}
|
||||
|
||||
dispatchName := that.Req.FormValue("dispatch_name")
|
||||
if dispatchName != "" {
|
||||
data["dispatch_name"] = dispatchName
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "ORDER": "release_time DESC"}
|
||||
}
|
||||
|
||||
count := that.Db.Count("article", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("article", "id,title,description,department_id,click_num+click_num_base AS click_num,"+
|
||||
"favorite_num_base+favorite_num AS favorite_num,dispatch_num,dispatch_name,prepare_date,release_time,expire_date,area_id,status,declare_id,declare_id,declare_id,dispatch_name,policy_level", data)
|
||||
for _, v := range res {
|
||||
|
||||
//if v.GetCeilInt("declare_id")>0{
|
||||
// v["declare"]=that.Db.Get("declare","id,tag",Map{"id":v.GetCeilInt("declare_id")})
|
||||
//}
|
||||
//if v.GetCeilInt("declare_id")>0{
|
||||
// v["declare"]=that.Db.Get("declare","tag",Map{"id":v.GetCeilInt("declare_id")})
|
||||
//}
|
||||
if v.GetCeilInt("declare_id") > 0 {
|
||||
v["declare"] = that.Db.Get("declare", "money_scope_min,money_scope_max,status", Map{"id": v.GetCeilInt("declare_id")})
|
||||
}
|
||||
}
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// Project 管理端项目
|
||||
var Project = Proj{
|
||||
"company": CompanyCtr,
|
||||
"declare": DeclareCtr,
|
||||
"matters": MattersCtr,
|
||||
"order": OrderCtr,
|
||||
"salesman": Salesman,
|
||||
"sms": Sms,
|
||||
"tag": TagCtr,
|
||||
"user": UserCtr,
|
||||
"wechat": Wechat,
|
||||
}
|
||||
|
||||
func strToArray(str string) Slice {
|
||||
s := Slice{}
|
||||
|
||||
olds := strings.Split(str, ",")
|
||||
for _, v := range olds {
|
||||
if v != "" {
|
||||
s = append(s, v)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func arrayToStr(ars Slice) string {
|
||||
s := ","
|
||||
if ars == nil {
|
||||
return s
|
||||
}
|
||||
for k, _ := range ars {
|
||||
s = s + ars.GetString(k) + ","
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
//生成随机码的6位md5
|
||||
func getSn() string {
|
||||
x := Rand(8)
|
||||
return Substr(Md5(ObjToStr(int64(x)+time.Now().UnixNano()+int64(Rand(6)))), 0, 6)
|
||||
}
|
||||
|
||||
//生成随机码的4位随机数
|
||||
func getCode() string {
|
||||
//res := ""
|
||||
//for i := 0; i < 4; i++ {
|
||||
res := ObjToStr(RandX(1000, 9999))
|
||||
//}
|
||||
return res
|
||||
}
|
||||
|
||||
// 过滤 emoji 表情
|
||||
func FilterEmoji(content string) string {
|
||||
new_content := ""
|
||||
for _, value := range content {
|
||||
_, size := utf8.DecodeRuneInString(string(value))
|
||||
if size <= 3 {
|
||||
new_content += string(value)
|
||||
}
|
||||
}
|
||||
return new_content
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var MattersCtr = Ctr{
|
||||
|
||||
"info": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("matters", "*", Map{"id": id})
|
||||
if res == nil {
|
||||
that.Display(4, "找不到事项")
|
||||
return
|
||||
}
|
||||
if res.GetCeilInt("salesman_id") != that.Session("salesman_id").ToCeilInt() {
|
||||
that.Display(4, "不是你的事项")
|
||||
return
|
||||
}
|
||||
|
||||
res["user"] = that.Db.Get("user", "id,name,nickname,company_id", Map{"id": res.GetCeilInt64("user_id")})
|
||||
if res.GetMap("user") != nil && res.GetMap("user").GetCeilInt64("company_id") != 0 {
|
||||
res["company"] = that.Db.Get("company", "id,name", Map{"id": res.GetMap("user").GetCeilInt64("company_id")})
|
||||
}
|
||||
that.Display(0, res)
|
||||
},
|
||||
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
userId := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
tp := that.Req.FormValue("type")
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "salesman_id": that.Session("salesman_id").Data}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"title[~]": keywords, "description[~]": keywords, "content[~]": keywords}
|
||||
}
|
||||
|
||||
if userId != 0 {
|
||||
|
||||
user := that.Db.Get("user", "id", Map{"AND": Map{"id": userId, "salesman_id": that.Session("salesman_id").Data}})
|
||||
if user != nil {
|
||||
data["user_id"] = userId
|
||||
}
|
||||
}
|
||||
|
||||
if tp != "" {
|
||||
data["type"] = ObjToInt("tp")
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["modify_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["modify_time[<=]"] = finishTime
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data}
|
||||
}
|
||||
|
||||
count := that.Db.Count("matters", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("matters", "*", data)
|
||||
|
||||
for _, v := range res {
|
||||
if v.GetCeilInt64("user_id") != 0 {
|
||||
v["user"] = that.Db.Get("user", "id,avatar,name,nickname,company_id", Map{"id": v.GetCeilInt64("user_id")})
|
||||
if v.GetMap("user") != nil && v.GetMap("user").GetCeilInt64("company_id") != 0 {
|
||||
v["company"] = that.Db.Get("company", "id,name", Map{"id": v.GetMap("user").GetCeilInt64("company_id")})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,239 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var OrderCtr = Ctr{
|
||||
"info": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
|
||||
if salesman == nil {
|
||||
that.Display(2, "登录错误")
|
||||
return
|
||||
}
|
||||
|
||||
res := that.Db.Get("order", "*", Map{"AND": Map{"id": id, "provider_id": salesman.GetCeilInt64("provider_id")}})
|
||||
|
||||
if res == nil {
|
||||
that.Display(4, "找不到对应订单")
|
||||
return
|
||||
}
|
||||
|
||||
//if res.GetCeilInt("salesman_id") != that.Session("salesman_id").ToCeilInt() {
|
||||
// that.Display(4, "不是你的订单")
|
||||
// return
|
||||
//}
|
||||
|
||||
if res.GetCeilInt("user_id") > 0 {
|
||||
res["user"] = that.Db.Get("user", "name,nickname,avatar", Map{"id": res.GetCeilInt("user_id")})
|
||||
}
|
||||
|
||||
res["order_record"] = that.Db.Select("order_record", "remarks,modify_time", Map{"order_id": res.GetCeilInt("id"), "ORDER": "modify_time DESC"})
|
||||
|
||||
that.Display(0, res)
|
||||
},
|
||||
"create_order_record": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
remarks := that.Req.FormValue("remarks")
|
||||
|
||||
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
|
||||
if salesman == nil {
|
||||
that.Display(2, "登录错误")
|
||||
return
|
||||
}
|
||||
|
||||
order := that.Db.Get("order", "*", Map{"AND": Map{"id": id, "provider_id": salesman.GetCeilInt64("provider_id")}})
|
||||
if order == nil {
|
||||
that.Display(4, "不是属于你的订单")
|
||||
return
|
||||
}
|
||||
|
||||
if order.GetCeilInt("status") != 0 {
|
||||
that.Display(4, "已完结订单,不可操作")
|
||||
return
|
||||
}
|
||||
|
||||
orderRecordId := that.Db.Insert("order_record", Map{
|
||||
"order_id": id,
|
||||
"user_id": order.GetCeilInt64("user_id"),
|
||||
"remarks": salesman.GetString("name") + ":" + remarks,
|
||||
"salesman_id": order.GetCeilInt64("salesman_id"),
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
})
|
||||
|
||||
that.Db.Update("order", Map{"order_record_id": orderRecordId}, Map{"id": id})
|
||||
|
||||
that.Display(0, "新增订单记录成功")
|
||||
|
||||
},
|
||||
"edit": func(that *Context) {
|
||||
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
id := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if id == 0 {
|
||||
that.Display(3, "请求参数异常")
|
||||
return
|
||||
}
|
||||
|
||||
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
|
||||
if salesman == nil {
|
||||
that.Display(2, "登录错误")
|
||||
return
|
||||
}
|
||||
|
||||
policyDeclareFlag := ObjToInt(that.Req.FormValue("policy_declare_flag"))
|
||||
declareId := ObjToInt(that.Req.FormValue("declare_id"))
|
||||
|
||||
intellectualPropertyFlag := ObjToInt(that.Req.FormValue("intellectual_property_flag"))
|
||||
intellectualPropertyCount := ObjToInt(that.Req.FormValue("intellectual_property_count"))
|
||||
taxOnsultingFlag := ObjToInt(that.Req.FormValue("tax_onsulting_flag"))
|
||||
|
||||
lawFlag := ObjToInt(that.Req.FormValue("law_flag"))
|
||||
status := ObjToInt(that.Req.FormValue("status"))
|
||||
|
||||
data := Map{
|
||||
"policy_declare_flag": policyDeclareFlag,
|
||||
"intellectual_property_flag": intellectualPropertyFlag,
|
||||
"intellectual_property_count": intellectualPropertyCount,
|
||||
"tax_onsulting_flag": taxOnsultingFlag,
|
||||
"law_flag": lawFlag,
|
||||
"status": status,
|
||||
"modify_time[#]": "now()",
|
||||
}
|
||||
|
||||
if declareId != 0 {
|
||||
data["declare_id"] = declareId
|
||||
}
|
||||
|
||||
order := that.Db.Get("order", "*", Map{"AND": Map{"id": id, "provider_id": salesman.GetCeilInt64("provider_id")}})
|
||||
if order == nil {
|
||||
that.Display(4, "不是属于你的订单")
|
||||
return
|
||||
}
|
||||
|
||||
if order.GetCeilInt("status") != 0 {
|
||||
that.Display(4, "已完结订单,不可操作")
|
||||
return
|
||||
}
|
||||
|
||||
data["order_record_id"] = that.Db.Insert("order_record", Map{
|
||||
"order_id": id,
|
||||
"user_id": order.GetCeilInt64("user_id"),
|
||||
"remarks": salesman.GetString("name") + "变更了订单服务内容",
|
||||
"salesman_id": order.GetCeilInt64("salesman_id"),
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
})
|
||||
re := that.Db.Update("order", data, Map{"id": id})
|
||||
if re == 0 {
|
||||
that.Display(4, "变更订单内容失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, "变更订单内容成功")
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
userId := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
|
||||
if salesman == nil {
|
||||
that.Display(2, "登录错误")
|
||||
return
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "provider_id": salesman.GetCeilInt64("provider_id")}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"sn[~]": keywords, "name[~]": keywords}
|
||||
}
|
||||
|
||||
if userId != 0 {
|
||||
|
||||
user := that.Db.Get("user", "id", Map{"AND": Map{"id": userId, "salesman_id": that.Session("salesman_id").Data}})
|
||||
if user != nil {
|
||||
data["user_id"] = userId
|
||||
}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["modify_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["modify_time[<=]"] = finishTime
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data}
|
||||
}
|
||||
|
||||
count := that.Db.Count("order", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("order", "*", data)
|
||||
for _, v := range res {
|
||||
|
||||
//if v.GetCeilInt("policy_id")>0{
|
||||
// v["policy"]=that.Db.Get("policy","id,tag",Map{"id":v.GetCeilInt("policy_id")})
|
||||
//}
|
||||
if v.GetCeilInt("user_id") > 0 {
|
||||
v["user"] = that.Db.Get("user", "name,nickname,avatar", Map{"id": v.GetCeilInt("user_id")})
|
||||
}
|
||||
if v.GetCeilInt("order_record_id") > 0 {
|
||||
v["order_record"] = that.Db.Get("order_record", "remarks,modify_time", Map{"id": v.GetCeilInt("order_record_id")})
|
||||
}
|
||||
}
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var Salesman = Ctr{
|
||||
"test": func(that *Context) {
|
||||
that.Session("salesman_id", 1)
|
||||
that.Session("wechat_id", 1)
|
||||
that.Display(0, 1)
|
||||
},
|
||||
"info": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
|
||||
if salesman == nil {
|
||||
that.Display(4, "找不到该业务员")
|
||||
return
|
||||
}
|
||||
|
||||
if salesman.GetString("nickname") == "" {
|
||||
wechat := that.Db.Get("wechat", "*", Map{"salesman_id": salesman.GetCeilInt64("id")})
|
||||
if wechat != nil {
|
||||
salesman["nickname"] = wechat.GetString("nickname")
|
||||
salesman["avatar"] = wechat.GetString("avatar")
|
||||
that.Db.Update("salesman", Map{"nickname": wechat.GetString("nickname"), "avatar": wechat.GetString("avatar")}, Map{"id": salesman.GetCeilInt64("id")})
|
||||
}
|
||||
}
|
||||
salesman["user"] = that.Db.Count("user", Map{"AND": Map{"salesman_id": that.Session("salesman_id").Data, "del_flag": 0}})
|
||||
salesman["matters"] = that.Db.Count("matters", Map{"AND": Map{"salesman_id": that.Session("salesman_id").Data, "del_flag": 0}})
|
||||
|
||||
salesman["admin"] = that.Db.Get("admin", "id,name,avatar", Map{"id": salesman.GetCeilInt64("admin_id")})
|
||||
salesman["provider"] = that.Db.Get("provider", "*", Map{"id": salesman.GetCeilInt64("provider_id")})
|
||||
if salesman["provider"] != nil {
|
||||
salesman["provider_salesman"] = that.Db.Get("salesman", "id,nickname,name,avatar", Map{"id": salesman.GetMap("provider").GetCeilInt64("salesman_id")})
|
||||
}
|
||||
|
||||
that.Display(0, salesman)
|
||||
},
|
||||
|
||||
"search": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
salesman := that.Db.Get("salesman", "*", Map{"id": that.Session("salesman_id").Data})
|
||||
if salesman == nil {
|
||||
that.Display(4, "找不到该业务员")
|
||||
return
|
||||
}
|
||||
|
||||
provider := that.Db.Get("provider", "*", Map{"id": salesman.GetCeilInt64("provider_id")})
|
||||
|
||||
if provider.GetCeilInt("salesman_id") != salesman.GetCeilInt("id") {
|
||||
that.Display(0, Slice{})
|
||||
return
|
||||
}
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "provider_id": salesman.GetCeilInt64("provider_id")}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"name[~]": keywords, "nickname[~]": keywords, "phone[~]": keywords}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["modifye_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["modifye_time[<=]"] = finishTime
|
||||
}
|
||||
|
||||
count := that.Db.Count("salesman", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("salesman", "id,name,nickname,avatar", data)
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"login": func(that *Context) {
|
||||
|
||||
code := that.Req.FormValue("code")
|
||||
phone := that.Req.FormValue("phone")
|
||||
|
||||
if phone != that.Session("phone").ToStr() && code == that.Session("code").ToStr() {
|
||||
that.Display(3, "手机号或者验证码错误")
|
||||
return
|
||||
}
|
||||
|
||||
if that.Session("wechat_id").Data == nil {
|
||||
that.Display(2, "还未登录")
|
||||
return
|
||||
}
|
||||
|
||||
wechat := that.Db.Get("wechat", "*", Map{"id": that.Session("wechat_id").ToCeilInt()})
|
||||
|
||||
salesman := that.Db.Get("salesman", "*", Map{"phone": phone})
|
||||
|
||||
if salesman == nil {
|
||||
that.Display(3, "找不到企服商")
|
||||
return
|
||||
}
|
||||
|
||||
if wechat == nil {
|
||||
that.Display(2, "还未绑定微信")
|
||||
return
|
||||
}
|
||||
|
||||
//有用户直接返回
|
||||
if wechat.GetCeilInt("salesman_id") != 0 && wechat.GetCeilInt64("salesman_id") != salesman.GetCeilInt64("id") {
|
||||
that.Display(5, "你已经绑定了其他商户")
|
||||
return
|
||||
}
|
||||
|
||||
that.Db.Update("wechat", Map{"salesman_id": salesman.GetCeilInt64("id")}, Map{"id": wechat.GetCeilInt64("id")})
|
||||
that.Db.Update("salesman", Map{"login_time[#]": "now()", "modify_time[#]": "now()"},
|
||||
Map{"id": salesman.GetCeilInt("id")})
|
||||
|
||||
wechat["salesman_id"] = salesman.GetCeilInt64("id")
|
||||
that.Session("salesman_id", salesman.GetCeilInt64("id"))
|
||||
that.Display(0, "登录成功!")
|
||||
|
||||
},
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
"code.hoteas.com/golang/hotime/common"
|
||||
"code.hoteas.com/golang/hotime/dri/ddsms"
|
||||
)
|
||||
|
||||
var Sms = Ctr{
|
||||
//只允许微信验证过的或者登录成功的发送短信
|
||||
"send": func(that *Context) {
|
||||
|
||||
phone := that.Req.FormValue("phone")
|
||||
if len(phone) < 11 {
|
||||
that.Display(3, "手机号格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
if that.Session("wechat_id").Data == nil && that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录不可发送短信")
|
||||
return
|
||||
}
|
||||
|
||||
salesman := that.Db.Get("salesman", "id", common.Map{"phone": phone})
|
||||
if salesman == nil {
|
||||
that.Display(3, "你还不是企服人员,请联系管理员")
|
||||
return
|
||||
}
|
||||
|
||||
code := getCode()
|
||||
that.Session("phone", phone)
|
||||
that.Session("code", code)
|
||||
|
||||
ddsms.DDY.SendYZM(phone, that.Config.GetString("smsLogin"), map[string]string{"code": code})
|
||||
|
||||
that.Display(0, "发送成功")
|
||||
},
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
)
|
||||
|
||||
var TagCtr = Ctr{
|
||||
|
||||
"create": func(that *Context) {
|
||||
if that.Session("user_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
name := that.Req.FormValue("name")
|
||||
|
||||
oldTag := that.Db.Get("tag", "id", Map{"name": name})
|
||||
if oldTag != nil {
|
||||
that.Display(4, "此标签已存在")
|
||||
return
|
||||
}
|
||||
|
||||
re := that.Db.Insert("tag", Map{
|
||||
"user_id": that.Session("user_id").Data,
|
||||
"name": name,
|
||||
"remark": "用户上传",
|
||||
"create_time[#]": "now()",
|
||||
"modify_time[#]": "now()",
|
||||
"state": 1, //先置为异常状态,等待审核通过
|
||||
"del_flag": 0,
|
||||
})
|
||||
|
||||
if re == 0 {
|
||||
that.Display(4, "添加失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(0, "添加成功")
|
||||
return
|
||||
|
||||
},
|
||||
//用户微信公众号或者小程序登录
|
||||
"search": func(that *Context) {
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 40
|
||||
}
|
||||
|
||||
data := Map{"del_flag": 0, "state": 0}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"name[~]": keywords, "remark[~]": keywords}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["modify_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["modify_time[<=]"] = finishTime
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data}
|
||||
}
|
||||
|
||||
count := that.Db.Count("tag", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("tag", "id,name,remark", data)
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"time"
|
||||
)
|
||||
|
||||
var UserCtr = Ctr{
|
||||
//用户微信公众号或者小程序登录
|
||||
"info": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
userId := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if userId == 0 {
|
||||
that.Display(3, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
user := that.Db.Get("user", "*", Map{"id": that.Session("user_id").ToCeilInt()})
|
||||
if user == nil {
|
||||
that.Display(4, "获取个人信息失败")
|
||||
return
|
||||
}
|
||||
|
||||
delete(user, "password")
|
||||
|
||||
that.Display(0, user)
|
||||
},
|
||||
|
||||
"edit": func(that *Context) {
|
||||
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
userId := ObjToInt(that.Req.FormValue("id"))
|
||||
|
||||
if userId == 0 {
|
||||
that.Display(3, "参数错误")
|
||||
return
|
||||
}
|
||||
|
||||
name := that.Req.FormValue("name")
|
||||
nickname := that.Req.FormValue("nickname")
|
||||
sex := that.Req.FormValue("sex")
|
||||
email := that.Req.FormValue("email")
|
||||
avatar := that.Req.FormValue("avatar")
|
||||
address := that.Req.FormValue("address")
|
||||
phone := that.Req.FormValue("phone") //如果更换手机号则要有新的短信验证码
|
||||
|
||||
data := Map{"modify_time[#]": "now()"}
|
||||
if name != "" {
|
||||
data["name"] = name
|
||||
}
|
||||
if nickname != "" {
|
||||
data["nickname"] = nickname
|
||||
}
|
||||
if sex != "" {
|
||||
data["sex"] = sex
|
||||
}
|
||||
if email != "" {
|
||||
data["email"] = email
|
||||
}
|
||||
if avatar != "" {
|
||||
data["avatar"] = avatar
|
||||
}
|
||||
if address != "" {
|
||||
data["address"] = address
|
||||
}
|
||||
if phone != "" {
|
||||
|
||||
data["phone"] = phone
|
||||
}
|
||||
|
||||
re := that.Db.Update("user", data, Map{"id": userId})
|
||||
if re == 0 {
|
||||
that.Display(4, "更新失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Display(4, "修改成功")
|
||||
},
|
||||
|
||||
"search": func(that *Context) {
|
||||
if that.Session("salesman_id").Data == nil {
|
||||
that.Display(2, "没有登录")
|
||||
return
|
||||
}
|
||||
|
||||
page := ObjToInt(that.Req.FormValue("page"))
|
||||
pageSize := ObjToInt(that.Req.FormValue("pageSize"))
|
||||
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
tp := ObjToInt(that.Req.FormValue("type")) //0,无操作,1,已扫码未认证,2,已认证,3,VIP会员
|
||||
|
||||
data := Map{"del_flag": 0, "salesman_id": that.Session("salesman_id").Data}
|
||||
keywords := that.Req.FormValue("keywords")
|
||||
if keywords != "" {
|
||||
data["OR"] = Map{"name[~]": keywords, "nickname[~]": keywords, "phone[~]": keywords}
|
||||
}
|
||||
|
||||
startTime := that.Req.FormValue("starttime")
|
||||
finishTime := that.Req.FormValue("finishtime")
|
||||
|
||||
if startTime != "" {
|
||||
data["modifye_time[>=]"] = startTime
|
||||
}
|
||||
if finishTime != "" {
|
||||
data["modifye_time[<=]"] = finishTime
|
||||
}
|
||||
if tp == 1 {
|
||||
data["certification_flag"] = 0
|
||||
}
|
||||
|
||||
if tp == 2 {
|
||||
data["certification_flag"] = 1
|
||||
data["OR"] = Map{"expiration_time": nil, "expiration_time[#]": "now()"}
|
||||
}
|
||||
|
||||
if tp == 3 {
|
||||
data["certification_flag"] = 1
|
||||
data["expiration_time[>]"] = time.Now().Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
if len(data) > 1 {
|
||||
data = Map{"AND": data, "ORDER": "modify_time DESC"}
|
||||
}
|
||||
|
||||
count := that.Db.Count("user", data)
|
||||
|
||||
res := that.Db.Page(page, pageSize).PageSelect("user", "*", data)
|
||||
|
||||
for _, v := range res {
|
||||
delete(v, "password")
|
||||
}
|
||||
|
||||
that.Display(0, Map{"total": count, "data": res})
|
||||
},
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
. "code.hoteas.com/golang/hotime"
|
||||
. "code.hoteas.com/golang/hotime/common"
|
||||
"code.hoteas.com/golang/hotime/dri/wechat"
|
||||
)
|
||||
|
||||
var Wechat = Ctr{
|
||||
|
||||
////微信注册
|
||||
"code": func(that *Context) {
|
||||
|
||||
if that.Req.FormValue("code") == "" {
|
||||
that.Display(3, "参数不足")
|
||||
return
|
||||
}
|
||||
|
||||
appid, resToken, userInfo, err := wechat.H5Program.GetUserInfo(that.Req.FormValue("code"))
|
||||
|
||||
if err != nil {
|
||||
that.Display(4, err)
|
||||
return
|
||||
}
|
||||
//此次获取的微信信息
|
||||
wechatInfo := Map{
|
||||
"openid": userInfo.OpenID,
|
||||
"acttoken": resToken.AccessToken,
|
||||
"retoken": resToken.RefreshToken,
|
||||
"appid": appid,
|
||||
"unionid": userInfo.Unionid,
|
||||
"nickname": FilterEmoji(userInfo.Nickname),
|
||||
"avatar": userInfo.HeadImgURL,
|
||||
//"create_time[#]":"now()",
|
||||
"modify_time[#]": "now()",
|
||||
"del_flag": 0,
|
||||
"type": 1,
|
||||
}
|
||||
|
||||
wechat := that.Db.Get("wechat", "*", Map{"AND": Map{"openid": userInfo.OpenID, "del_flag": 0}})
|
||||
|
||||
if wechat != nil {
|
||||
//有用户直接返回
|
||||
if wechat.GetCeilInt("salesman_id") != 0 {
|
||||
|
||||
that.Db.Update("salesman", Map{"login_time[#]": "now()"},
|
||||
Map{"id": wechat.GetCeilInt("salesman_id")})
|
||||
that.Session("salesman_id", wechat.GetCeilInt("salesman_id"))
|
||||
|
||||
that.Display(0, "登录成功")
|
||||
return
|
||||
}
|
||||
that.Session("wechat_id", wechat.GetCeilInt("id"))
|
||||
that.Display(2, "暂未绑定")
|
||||
return
|
||||
|
||||
}
|
||||
|
||||
wechatInfo["create_time[#]"] = "now()"
|
||||
|
||||
wechatInfo["id"] = that.Db.Insert("wechat", wechatInfo)
|
||||
if wechatInfo.GetCeilInt("id") == 0 {
|
||||
that.Display(4, "创建用户失败")
|
||||
return
|
||||
}
|
||||
|
||||
that.Session("wechat_id", wechatInfo.GetCeilInt("id"))
|
||||
that.Display(2, "暂未绑定")
|
||||
},
|
||||
|
||||
//网页签名
|
||||
"sign": func(that *Context) {
|
||||
|
||||
signUrl := that.Req.FormValue("url")
|
||||
if signUrl == "" {
|
||||
that.Display(3, "参数不足")
|
||||
return
|
||||
}
|
||||
|
||||
cfg1, e := wechat.H5Program.GetSignUrl(signUrl)
|
||||
|
||||
if e != nil {
|
||||
that.Display(4, e)
|
||||
return
|
||||
}
|
||||
|
||||
sign := Map{
|
||||
"appId": cfg1.AppID,
|
||||
"timestamp": cfg1.Timestamp,
|
||||
"nonceStr": cfg1.NonceStr,
|
||||
"signature": cfg1.Signature,
|
||||
}
|
||||
|
||||
that.Display(0, sign)
|
||||
|
||||
},
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>微信登录</title>
|
||||
<meta charset="utf-8">
|
||||
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
|
||||
<script type="text/javascript" src="js/hotime.js"></script>
|
||||
<script type="text/javascript" src="js/qrcode.min.js"></script>
|
||||
<style>
|
||||
body{margin:0;}
|
||||
.box{width:100%;height: 100vh;display:flex;align-items:center;justify-content: center;position: relative;}
|
||||
.logo{position: absolute;top:7px;left: 17px;z-index: 2;width: 62px;height:22px;}
|
||||
.logo img{width:100%;background-size: contain;}
|
||||
.bg-img{position: absolute;top:0;left:0;width:100%;background-size: contain;}
|
||||
.title{font-size: 14px;font-weight: bold;color: #FFF;letter-spacing: 6px;margin-bottom:50px;text-align: center;}
|
||||
#qrcode{width:117px; height:117px; margin:23px auto 40px;}
|
||||
.content{background: #D0ECF9;border: 1px solid rgba(255, 255, 255, 0.6);box-shadow: 0px 4px 12px rgba(25, 105, 146, 0.24);border-radius: 8px;padding:34px 0;font-size: 18px;color: #0674AE;margin:0 auto;width:65%;text-align: center;}
|
||||
.footer{position: fixed;bottom:14px;width: 100%;font-size: 12px;
|
||||
color: rgba(0, 0, 0, 0.7);text-align: center;line-height: 16px;}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="box">
|
||||
<div class="logo">
|
||||
<img src="./img/logo_2@2x.png" alt="">
|
||||
</div>
|
||||
<img class="bg-img" src="./img/bg_up@2x.png">
|
||||
<div style="flex:1;">
|
||||
<div class="title">
|
||||
欢迎使用政策狩猎精灵
|
||||
</div>
|
||||
<div class="content">
|
||||
<div>初次使用需要绑定您的信息</div>
|
||||
<div>请打开微信扫描下方二维码</div>
|
||||
<div id="qrcode"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="footer">
|
||||
<div>成都市创新创业服务平台</div>
|
||||
<div>国家级双创示范平台</div>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
var qrcode = new QRCode(document.getElementById("qrcode"), {
|
||||
width: 117,
|
||||
height: 117
|
||||
})
|
||||
function run() {
|
||||
var data={"timestamp": window.H.getParam("timestamp"),"sn":window.H.getParam("sn")}
|
||||
// if(data.code==null){
|
||||
// location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4d97696b9ecb49fc&redirect_uri='+location.href+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect'
|
||||
// return
|
||||
// }
|
||||
|
||||
//定时器,3s刷新登录
|
||||
window.H.post("/app/upan/login", data, function (res) {
|
||||
if (res.status != 0) {
|
||||
//展示二维码,链接扫码到一个页面传参timestamp&sn,页面内容:app/upan/create?timestamp&sn&phone&company_name&code,成功后跳转到首页
|
||||
|
||||
let url = 'https://'+location.host+'/#/qrcode?timestamp='+ window.H.getParam("timestamp")+"&sn="+ encodeURIComponent(window.H.getParam("sn"))
|
||||
qrcode.makeCode(url)
|
||||
setTimeout(function(){
|
||||
run()
|
||||
},3000)
|
||||
return
|
||||
}
|
||||
// let res = { "result": { "acttoken": "56_ogEfWa4mglG-Ilf2kD50FfekZWimJXUouZ4gMKmkVP2CwcLwv2lHO35LOn5NSLOQ-yEAZcIs3FvgIBhk2uF9CA", "appid": "wx4d97696b9ecb49fc", "avatar": "https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLNj0yKXe77H8C60ic2lUFIx5hkibf0FluNCRfTkiazrBfuqclqRhm4nDug9Hx3nsXQhtzNdfchAvJTQ/132", "nickname": "候鸟半夏", "openid": "oPoZT6juCkF6fvnMHrCFI6SK_vK8", "retoken": "56_tjuJPobvbLVvOPtqPRZjTzQHR7i3Vmx_aGXOy9j0WsNTFS_JRnb4ArmUGhWtq6e7eCpUnPNKulIQ44CPiBnYEA", "unionid": "ofKK36PEkbIt0xMMUgch4H-bVaFI" }, "status": 0 }
|
||||
location.href="/#/home"
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
run()
|
||||
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -3,6 +3,7 @@ module code.hoteas.com/golang/hotime
|
||||
go 1.16
|
||||
|
||||
require (
|
||||
github.com/360EntSecGroup-Skylar/excelize v1.4.1
|
||||
github.com/garyburd/redigo v1.6.3
|
||||
github.com/go-pay/gopay v1.5.78
|
||||
github.com/go-sql-driver/mysql v1.6.0
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
github.com/360EntSecGroup-Skylar/excelize v1.4.1 h1:l55mJb6rkkaUzOpSsgEeKYtS6/0gHwBYyfo5Jcjv/Ks=
|
||||
github.com/360EntSecGroup-Skylar/excelize v1.4.1/go.mod h1:vnax29X2usfl7HHkBrX5EvSCJcmH3dT9luvxzu8iGAE=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
@@ -21,6 +23,8 @@ github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/mattn/go-sqlite3 v1.14.12 h1:TJ1bhYJPV44phC+IMu1u2K/i5RriLTPe+yc68XDJ1Z0=
|
||||
github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 h1:RWengNIwukTxcDr9M+97sNutRR1RKhG96O6jWumTTnw=
|
||||
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826/go.mod h1:TaXosZuwdSHYgviHp1DAtfrULt5eUgsSMsZf+YrPgl8=
|
||||
github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms=
|
||||
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
@@ -33,6 +37,7 @@ github.com/spf13/cast v1.3.1 h1:nFm6S0SMdyzrzcmThSipiEubIDy8WEXKNZ0UOgiRpng=
|
||||
github.com/spf13/cast v1.3.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.2.3-0.20181224173747-660f15d67dbb/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
|
||||
+22
-3
@@ -82,10 +82,29 @@ func findCaller(skip int) string {
|
||||
for i := 0; i < 10; i++ {
|
||||
file, line = getCaller(skip + i)
|
||||
if !strings.HasPrefix(file, "logrus") {
|
||||
|
||||
if file == "common/error.go" {
|
||||
file, line = getCaller(skip + i + 1)
|
||||
j := 0
|
||||
for true {
|
||||
j++
|
||||
if file == "common/error.go" {
|
||||
file, line = getCaller(skip + i + j)
|
||||
}
|
||||
if file == "db/hotimedb.go" {
|
||||
file, line = getCaller(skip + i + j)
|
||||
}
|
||||
if file == "code/makecode.go" {
|
||||
file, line = getCaller(skip + i + j)
|
||||
}
|
||||
if strings.Index(file, "common/") == 0 {
|
||||
file, line = getCaller(skip + i + j)
|
||||
}
|
||||
if strings.Contains(file, "application.go") {
|
||||
file, line = getCaller(skip + i + j)
|
||||
}
|
||||
if j == 5 {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ var Config = Map{
|
||||
Map{
|
||||
"table": "admin", //默认admin,必须,有则根据数据库内当前表名做为用户生成数据
|
||||
"name": "", //默认admin,非必须,有则生成代码到此目录,无则采用缺省模式使用表名
|
||||
"config": "config/app.json", //默认config/app.json,必须,接口描述配置文件
|
||||
"config": "config/app.json", //默认config/app.json,必须,接口描述配置文件,无则自动生成
|
||||
"rule": "config/rule.json", //默认config/rule.json,非必须,有则按改规则生成接口,无则按系统内嵌方式生成
|
||||
"mode": 0, //默认0,非必须,0为内嵌代码模式,1为生成代码模式
|
||||
},
|
||||
@@ -65,11 +65,12 @@ var ConfigNote = Map{
|
||||
"注释:配置即启用,非必须,默认无",
|
||||
Map{ //默认无,必须,接口类别名称
|
||||
//"注释": "", //
|
||||
"table": "默认admin,必须,根据数据库内当前表名做为用户生成数据",
|
||||
"name": "默认无,非必须,有则生成代码到此目录,无则采用缺省模式使用表名,如设置为:admin,将在admin目录生成包名为admin的代码",
|
||||
"config": "默认config/app.json,必须,接口描述配置文件", //
|
||||
"rule": "默认config/rule.json,非必须,有则按改规则生成接口,无则按系统内嵌方式生成",
|
||||
"mode": "默认0,非必须,0为内嵌代码模式,1为生成代码模式",
|
||||
"table": "默认admin,必须,根据数据库内当前表名做为用户生成数据",
|
||||
"name": "默认无,非必须,有则生成代码到此目录,无则采用缺省模式使用表名,如设置为:admin,将在admin目录生成包名为admin的代码",
|
||||
"config": "默认config/app.json,必须,接口描述配置文件", //
|
||||
"configDB": "默认无,非必须,有则每次将数据库数据生成到此目录用于配置读写,无则不生成", //
|
||||
"rule": "默认config/rule.json,非必须,有则按改规则生成接口,无则按系统内嵌方式生成",
|
||||
"mode": "默认0,非必须,0为内嵌代码模式,1为生成代码模式",
|
||||
},
|
||||
},
|
||||
"db": Map{
|
||||
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+718
@@ -0,0 +1,718 @@
|
||||
/*
|
||||
Copyright 2011 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
// Package memcache provides a client for the memcached cache server.
|
||||
package memcache
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Similar to:
|
||||
// https://godoc.org/google.golang.org/appengine/memcache
|
||||
|
||||
var (
|
||||
// ErrCacheMiss means that a Get failed because the item wasn't present.
|
||||
ErrCacheMiss = errors.New("memcache: cache miss")
|
||||
|
||||
// ErrCASConflict means that a CompareAndSwap call failed due to the
|
||||
// cached value being modified between the Get and the CompareAndSwap.
|
||||
// If the cached value was simply evicted rather than replaced,
|
||||
// ErrNotStored will be returned instead.
|
||||
ErrCASConflict = errors.New("memcache: compare-and-swap conflict")
|
||||
|
||||
// ErrNotStored means that a conditional write operation (i.e. Add or
|
||||
// CompareAndSwap) failed because the condition was not satisfied.
|
||||
ErrNotStored = errors.New("memcache: item not stored")
|
||||
|
||||
// ErrServer means that a server error occurred.
|
||||
ErrServerError = errors.New("memcache: server error")
|
||||
|
||||
// ErrNoStats means that no statistics were available.
|
||||
ErrNoStats = errors.New("memcache: no statistics available")
|
||||
|
||||
// ErrMalformedKey is returned when an invalid key is used.
|
||||
// Keys must be at maximum 250 bytes long and not
|
||||
// contain whitespace or control characters.
|
||||
ErrMalformedKey = errors.New("malformed: key is too long or contains invalid characters")
|
||||
|
||||
// ErrNoServers is returned when no servers are configured or available.
|
||||
ErrNoServers = errors.New("memcache: no servers configured or available")
|
||||
)
|
||||
|
||||
const (
|
||||
// DefaultTimeout is the default socket read/write timeout.
|
||||
DefaultTimeout = 100 * time.Millisecond
|
||||
|
||||
// DefaultMaxIdleConns is the default maximum number of idle connections
|
||||
// kept for any single address.
|
||||
DefaultMaxIdleConns = 2
|
||||
)
|
||||
|
||||
const buffered = 8 // arbitrary buffered channel size, for readability
|
||||
|
||||
// resumableError returns true if err is only a protocol-level cache error.
|
||||
// This is used to determine whether or not a server connection should
|
||||
// be re-used or not. If an error occurs, by default we don't reuse the
|
||||
// connection, unless it was just a cache error.
|
||||
func resumableError(err error) bool {
|
||||
switch err {
|
||||
case ErrCacheMiss, ErrCASConflict, ErrNotStored, ErrMalformedKey:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func legalKey(key string) bool {
|
||||
if len(key) > 250 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(key); i++ {
|
||||
if key[i] <= ' ' || key[i] == 0x7f {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
var (
|
||||
crlf = []byte("\r\n")
|
||||
space = []byte(" ")
|
||||
resultOK = []byte("OK\r\n")
|
||||
resultStored = []byte("STORED\r\n")
|
||||
resultNotStored = []byte("NOT_STORED\r\n")
|
||||
resultExists = []byte("EXISTS\r\n")
|
||||
resultNotFound = []byte("NOT_FOUND\r\n")
|
||||
resultDeleted = []byte("DELETED\r\n")
|
||||
resultEnd = []byte("END\r\n")
|
||||
resultOk = []byte("OK\r\n")
|
||||
resultTouched = []byte("TOUCHED\r\n")
|
||||
|
||||
resultClientErrorPrefix = []byte("CLIENT_ERROR ")
|
||||
versionPrefix = []byte("VERSION")
|
||||
)
|
||||
|
||||
// New returns a memcache client using the provided server(s)
|
||||
// with equal weight. If a server is listed multiple times,
|
||||
// it gets a proportional amount of weight.
|
||||
func New(server ...string) *Client {
|
||||
ss := new(ServerList)
|
||||
ss.SetServers(server...)
|
||||
return NewFromSelector(ss)
|
||||
}
|
||||
|
||||
// NewFromSelector returns a new Client using the provided ServerSelector.
|
||||
func NewFromSelector(ss ServerSelector) *Client {
|
||||
return &Client{selector: ss}
|
||||
}
|
||||
|
||||
// Client is a memcache client.
|
||||
// It is safe for unlocked use by multiple concurrent goroutines.
|
||||
type Client struct {
|
||||
// Timeout specifies the socket read/write timeout.
|
||||
// If zero, DefaultTimeout is used.
|
||||
Timeout time.Duration
|
||||
|
||||
// MaxIdleConns specifies the maximum number of idle connections that will
|
||||
// be maintained per address. If less than one, DefaultMaxIdleConns will be
|
||||
// used.
|
||||
//
|
||||
// Consider your expected traffic rates and latency carefully. This should
|
||||
// be set to a number higher than your peak parallel requests.
|
||||
MaxIdleConns int
|
||||
|
||||
selector ServerSelector
|
||||
|
||||
lk sync.Mutex
|
||||
freeconn map[string][]*conn
|
||||
}
|
||||
|
||||
// Item is an item to be got or stored in a memcached server.
|
||||
type Item struct {
|
||||
// Key is the Item's key (250 bytes maximum).
|
||||
Key string
|
||||
|
||||
// Value is the Item's value.
|
||||
Value []byte
|
||||
|
||||
// Flags are server-opaque flags whose semantics are entirely
|
||||
// up to the app.
|
||||
Flags uint32
|
||||
|
||||
// Expiration is the cache expiration time, in seconds: either a relative
|
||||
// time from now (up to 1 month), or an absolute Unix epoch time.
|
||||
// Zero means the Item has no expiration time.
|
||||
Expiration int32
|
||||
|
||||
// Compare and swap ID.
|
||||
casid uint64
|
||||
}
|
||||
|
||||
// conn is a connection to a server.
|
||||
type conn struct {
|
||||
nc net.Conn
|
||||
rw *bufio.ReadWriter
|
||||
addr net.Addr
|
||||
c *Client
|
||||
}
|
||||
|
||||
// release returns this connection back to the client's free pool
|
||||
func (cn *conn) release() {
|
||||
cn.c.putFreeConn(cn.addr, cn)
|
||||
}
|
||||
|
||||
func (cn *conn) extendDeadline() {
|
||||
cn.nc.SetDeadline(time.Now().Add(cn.c.netTimeout()))
|
||||
}
|
||||
|
||||
// condRelease releases this connection if the error pointed to by err
|
||||
// is nil (not an error) or is only a protocol level error (e.g. a
|
||||
// cache miss). The purpose is to not recycle TCP connections that
|
||||
// are bad.
|
||||
func (cn *conn) condRelease(err *error) {
|
||||
if *err == nil || resumableError(*err) {
|
||||
cn.release()
|
||||
} else {
|
||||
cn.nc.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) putFreeConn(addr net.Addr, cn *conn) {
|
||||
c.lk.Lock()
|
||||
defer c.lk.Unlock()
|
||||
if c.freeconn == nil {
|
||||
c.freeconn = make(map[string][]*conn)
|
||||
}
|
||||
freelist := c.freeconn[addr.String()]
|
||||
if len(freelist) >= c.maxIdleConns() {
|
||||
cn.nc.Close()
|
||||
return
|
||||
}
|
||||
c.freeconn[addr.String()] = append(freelist, cn)
|
||||
}
|
||||
|
||||
func (c *Client) getFreeConn(addr net.Addr) (cn *conn, ok bool) {
|
||||
c.lk.Lock()
|
||||
defer c.lk.Unlock()
|
||||
if c.freeconn == nil {
|
||||
return nil, false
|
||||
}
|
||||
freelist, ok := c.freeconn[addr.String()]
|
||||
if !ok || len(freelist) == 0 {
|
||||
return nil, false
|
||||
}
|
||||
cn = freelist[len(freelist)-1]
|
||||
c.freeconn[addr.String()] = freelist[:len(freelist)-1]
|
||||
return cn, true
|
||||
}
|
||||
|
||||
func (c *Client) netTimeout() time.Duration {
|
||||
if c.Timeout != 0 {
|
||||
return c.Timeout
|
||||
}
|
||||
return DefaultTimeout
|
||||
}
|
||||
|
||||
func (c *Client) maxIdleConns() int {
|
||||
if c.MaxIdleConns > 0 {
|
||||
return c.MaxIdleConns
|
||||
}
|
||||
return DefaultMaxIdleConns
|
||||
}
|
||||
|
||||
// ConnectTimeoutError is the error type used when it takes
|
||||
// too long to connect to the desired host. This level of
|
||||
// detail can generally be ignored.
|
||||
type ConnectTimeoutError struct {
|
||||
Addr net.Addr
|
||||
}
|
||||
|
||||
func (cte *ConnectTimeoutError) Error() string {
|
||||
return "memcache: connect timeout to " + cte.Addr.String()
|
||||
}
|
||||
|
||||
func (c *Client) dial(addr net.Addr) (net.Conn, error) {
|
||||
type connError struct {
|
||||
cn net.Conn
|
||||
err error
|
||||
}
|
||||
|
||||
nc, err := net.DialTimeout(addr.Network(), addr.String(), c.netTimeout())
|
||||
if err == nil {
|
||||
return nc, nil
|
||||
}
|
||||
|
||||
if ne, ok := err.(net.Error); ok && ne.Timeout() {
|
||||
return nil, &ConnectTimeoutError{addr}
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (c *Client) getConn(addr net.Addr) (*conn, error) {
|
||||
cn, ok := c.getFreeConn(addr)
|
||||
if ok {
|
||||
cn.extendDeadline()
|
||||
return cn, nil
|
||||
}
|
||||
nc, err := c.dial(addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cn = &conn{
|
||||
nc: nc,
|
||||
addr: addr,
|
||||
rw: bufio.NewReadWriter(bufio.NewReader(nc), bufio.NewWriter(nc)),
|
||||
c: c,
|
||||
}
|
||||
cn.extendDeadline()
|
||||
return cn, nil
|
||||
}
|
||||
|
||||
func (c *Client) onItem(item *Item, fn func(*Client, *bufio.ReadWriter, *Item) error) error {
|
||||
addr, err := c.selector.PickServer(item.Key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cn, err := c.getConn(addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cn.condRelease(&err)
|
||||
if err = fn(c, cn.rw, item); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) FlushAll() error {
|
||||
return c.selector.Each(c.flushAllFromAddr)
|
||||
}
|
||||
|
||||
// Get gets the item for the given key. ErrCacheMiss is returned for a
|
||||
// memcache cache miss. The key must be at most 250 bytes in length.
|
||||
func (c *Client) Get(key string) (item *Item, err error) {
|
||||
err = c.withKeyAddr(key, func(addr net.Addr) error {
|
||||
return c.getFromAddr(addr, []string{key}, func(it *Item) { item = it })
|
||||
})
|
||||
if err == nil && item == nil {
|
||||
err = ErrCacheMiss
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Touch updates the expiry for the given key. The seconds parameter is either
|
||||
// a Unix timestamp or, if seconds is less than 1 month, the number of seconds
|
||||
// into the future at which time the item will expire. Zero means the item has
|
||||
// no expiration time. ErrCacheMiss is returned if the key is not in the cache.
|
||||
// The key must be at most 250 bytes in length.
|
||||
func (c *Client) Touch(key string, seconds int32) (err error) {
|
||||
return c.withKeyAddr(key, func(addr net.Addr) error {
|
||||
return c.touchFromAddr(addr, []string{key}, seconds)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Client) withKeyAddr(key string, fn func(net.Addr) error) (err error) {
|
||||
if !legalKey(key) {
|
||||
return ErrMalformedKey
|
||||
}
|
||||
addr, err := c.selector.PickServer(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fn(addr)
|
||||
}
|
||||
|
||||
func (c *Client) withAddrRw(addr net.Addr, fn func(*bufio.ReadWriter) error) (err error) {
|
||||
cn, err := c.getConn(addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer cn.condRelease(&err)
|
||||
return fn(cn.rw)
|
||||
}
|
||||
|
||||
func (c *Client) withKeyRw(key string, fn func(*bufio.ReadWriter) error) error {
|
||||
return c.withKeyAddr(key, func(addr net.Addr) error {
|
||||
return c.withAddrRw(addr, fn)
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Client) getFromAddr(addr net.Addr, keys []string, cb func(*Item)) error {
|
||||
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
|
||||
if _, err := fmt.Fprintf(rw, "gets %s\r\n", strings.Join(keys, " ")); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rw.Flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := parseGetResponse(rw.Reader, cb); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// flushAllFromAddr send the flush_all command to the given addr
|
||||
func (c *Client) flushAllFromAddr(addr net.Addr) error {
|
||||
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
|
||||
if _, err := fmt.Fprintf(rw, "flush_all\r\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rw.Flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
line, err := rw.ReadSlice('\n')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case bytes.Equal(line, resultOk):
|
||||
break
|
||||
default:
|
||||
return fmt.Errorf("memcache: unexpected response line from flush_all: %q", string(line))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// ping sends the version command to the given addr
|
||||
func (c *Client) ping(addr net.Addr) error {
|
||||
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
|
||||
if _, err := fmt.Fprintf(rw, "version\r\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rw.Flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
line, err := rw.ReadSlice('\n')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch {
|
||||
case bytes.HasPrefix(line, versionPrefix):
|
||||
break
|
||||
default:
|
||||
return fmt.Errorf("memcache: unexpected response line from ping: %q", string(line))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (c *Client) touchFromAddr(addr net.Addr, keys []string, expiration int32) error {
|
||||
return c.withAddrRw(addr, func(rw *bufio.ReadWriter) error {
|
||||
for _, key := range keys {
|
||||
if _, err := fmt.Fprintf(rw, "touch %s %d\r\n", key, expiration); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rw.Flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
line, err := rw.ReadSlice('\n')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case bytes.Equal(line, resultTouched):
|
||||
break
|
||||
case bytes.Equal(line, resultNotFound):
|
||||
return ErrCacheMiss
|
||||
default:
|
||||
return fmt.Errorf("memcache: unexpected response line from touch: %q", string(line))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
// GetMulti is a batch version of Get. The returned map from keys to
|
||||
// items may have fewer elements than the input slice, due to memcache
|
||||
// cache misses. Each key must be at most 250 bytes in length.
|
||||
// If no error is returned, the returned map will also be non-nil.
|
||||
func (c *Client) GetMulti(keys []string) (map[string]*Item, error) {
|
||||
var lk sync.Mutex
|
||||
m := make(map[string]*Item)
|
||||
addItemToMap := func(it *Item) {
|
||||
lk.Lock()
|
||||
defer lk.Unlock()
|
||||
m[it.Key] = it
|
||||
}
|
||||
|
||||
keyMap := make(map[net.Addr][]string)
|
||||
for _, key := range keys {
|
||||
if !legalKey(key) {
|
||||
return nil, ErrMalformedKey
|
||||
}
|
||||
addr, err := c.selector.PickServer(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keyMap[addr] = append(keyMap[addr], key)
|
||||
}
|
||||
|
||||
ch := make(chan error, buffered)
|
||||
for addr, keys := range keyMap {
|
||||
go func(addr net.Addr, keys []string) {
|
||||
ch <- c.getFromAddr(addr, keys, addItemToMap)
|
||||
}(addr, keys)
|
||||
}
|
||||
|
||||
var err error
|
||||
for _ = range keyMap {
|
||||
if ge := <-ch; ge != nil {
|
||||
err = ge
|
||||
}
|
||||
}
|
||||
return m, err
|
||||
}
|
||||
|
||||
// parseGetResponse reads a GET response from r and calls cb for each
|
||||
// read and allocated Item
|
||||
func parseGetResponse(r *bufio.Reader, cb func(*Item)) error {
|
||||
for {
|
||||
line, err := r.ReadSlice('\n')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if bytes.Equal(line, resultEnd) {
|
||||
return nil
|
||||
}
|
||||
it := new(Item)
|
||||
size, err := scanGetResponseLine(line, it)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
it.Value = make([]byte, size+2)
|
||||
_, err = io.ReadFull(r, it.Value)
|
||||
if err != nil {
|
||||
it.Value = nil
|
||||
return err
|
||||
}
|
||||
if !bytes.HasSuffix(it.Value, crlf) {
|
||||
it.Value = nil
|
||||
return fmt.Errorf("memcache: corrupt get result read")
|
||||
}
|
||||
it.Value = it.Value[:size]
|
||||
cb(it)
|
||||
}
|
||||
}
|
||||
|
||||
// scanGetResponseLine populates it and returns the declared size of the item.
|
||||
// It does not read the bytes of the item.
|
||||
func scanGetResponseLine(line []byte, it *Item) (size int, err error) {
|
||||
pattern := "VALUE %s %d %d %d\r\n"
|
||||
dest := []interface{}{&it.Key, &it.Flags, &size, &it.casid}
|
||||
if bytes.Count(line, space) == 3 {
|
||||
pattern = "VALUE %s %d %d\r\n"
|
||||
dest = dest[:3]
|
||||
}
|
||||
n, err := fmt.Sscanf(string(line), pattern, dest...)
|
||||
if err != nil || n != len(dest) {
|
||||
return -1, fmt.Errorf("memcache: unexpected line in get response: %q", line)
|
||||
}
|
||||
return size, nil
|
||||
}
|
||||
|
||||
// Set writes the given item, unconditionally.
|
||||
func (c *Client) Set(item *Item) error {
|
||||
return c.onItem(item, (*Client).set)
|
||||
}
|
||||
|
||||
func (c *Client) set(rw *bufio.ReadWriter, item *Item) error {
|
||||
return c.populateOne(rw, "set", item)
|
||||
}
|
||||
|
||||
// Add writes the given item, if no value already exists for its
|
||||
// key. ErrNotStored is returned if that condition is not met.
|
||||
func (c *Client) Add(item *Item) error {
|
||||
return c.onItem(item, (*Client).add)
|
||||
}
|
||||
|
||||
func (c *Client) add(rw *bufio.ReadWriter, item *Item) error {
|
||||
return c.populateOne(rw, "add", item)
|
||||
}
|
||||
|
||||
// Replace writes the given item, but only if the server *does*
|
||||
// already hold data for this key
|
||||
func (c *Client) Replace(item *Item) error {
|
||||
return c.onItem(item, (*Client).replace)
|
||||
}
|
||||
|
||||
func (c *Client) replace(rw *bufio.ReadWriter, item *Item) error {
|
||||
return c.populateOne(rw, "replace", item)
|
||||
}
|
||||
|
||||
// CompareAndSwap writes the given item that was previously returned
|
||||
// by Get, if the value was neither modified or evicted between the
|
||||
// Get and the CompareAndSwap calls. The item's Key should not change
|
||||
// between calls but all other item fields may differ. ErrCASConflict
|
||||
// is returned if the value was modified in between the
|
||||
// calls. ErrNotStored is returned if the value was evicted in between
|
||||
// the calls.
|
||||
func (c *Client) CompareAndSwap(item *Item) error {
|
||||
return c.onItem(item, (*Client).cas)
|
||||
}
|
||||
|
||||
func (c *Client) cas(rw *bufio.ReadWriter, item *Item) error {
|
||||
return c.populateOne(rw, "cas", item)
|
||||
}
|
||||
|
||||
func (c *Client) populateOne(rw *bufio.ReadWriter, verb string, item *Item) error {
|
||||
if !legalKey(item.Key) {
|
||||
return ErrMalformedKey
|
||||
}
|
||||
var err error
|
||||
if verb == "cas" {
|
||||
_, err = fmt.Fprintf(rw, "%s %s %d %d %d %d\r\n",
|
||||
verb, item.Key, item.Flags, item.Expiration, len(item.Value), item.casid)
|
||||
} else {
|
||||
_, err = fmt.Fprintf(rw, "%s %s %d %d %d\r\n",
|
||||
verb, item.Key, item.Flags, item.Expiration, len(item.Value))
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = rw.Write(item.Value); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := rw.Write(crlf); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := rw.Flush(); err != nil {
|
||||
return err
|
||||
}
|
||||
line, err := rw.ReadSlice('\n')
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case bytes.Equal(line, resultStored):
|
||||
return nil
|
||||
case bytes.Equal(line, resultNotStored):
|
||||
return ErrNotStored
|
||||
case bytes.Equal(line, resultExists):
|
||||
return ErrCASConflict
|
||||
case bytes.Equal(line, resultNotFound):
|
||||
return ErrCacheMiss
|
||||
}
|
||||
return fmt.Errorf("memcache: unexpected response line from %q: %q", verb, string(line))
|
||||
}
|
||||
|
||||
func writeReadLine(rw *bufio.ReadWriter, format string, args ...interface{}) ([]byte, error) {
|
||||
_, err := fmt.Fprintf(rw, format, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rw.Flush(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
line, err := rw.ReadSlice('\n')
|
||||
return line, err
|
||||
}
|
||||
|
||||
func writeExpectf(rw *bufio.ReadWriter, expect []byte, format string, args ...interface{}) error {
|
||||
line, err := writeReadLine(rw, format, args...)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case bytes.Equal(line, resultOK):
|
||||
return nil
|
||||
case bytes.Equal(line, expect):
|
||||
return nil
|
||||
case bytes.Equal(line, resultNotStored):
|
||||
return ErrNotStored
|
||||
case bytes.Equal(line, resultExists):
|
||||
return ErrCASConflict
|
||||
case bytes.Equal(line, resultNotFound):
|
||||
return ErrCacheMiss
|
||||
}
|
||||
return fmt.Errorf("memcache: unexpected response line: %q", string(line))
|
||||
}
|
||||
|
||||
// Delete deletes the item with the provided key. The error ErrCacheMiss is
|
||||
// returned if the item didn't already exist in the cache.
|
||||
func (c *Client) Delete(key string) error {
|
||||
return c.withKeyRw(key, func(rw *bufio.ReadWriter) error {
|
||||
return writeExpectf(rw, resultDeleted, "delete %s\r\n", key)
|
||||
})
|
||||
}
|
||||
|
||||
// DeleteAll deletes all items in the cache.
|
||||
func (c *Client) DeleteAll() error {
|
||||
return c.withKeyRw("", func(rw *bufio.ReadWriter) error {
|
||||
return writeExpectf(rw, resultDeleted, "flush_all\r\n")
|
||||
})
|
||||
}
|
||||
|
||||
// Ping checks all instances if they are alive. Returns error if any
|
||||
// of them is down.
|
||||
func (c *Client) Ping() error {
|
||||
return c.selector.Each(c.ping)
|
||||
}
|
||||
|
||||
// Increment atomically increments key by delta. The return value is
|
||||
// the new value after being incremented or an error. If the value
|
||||
// didn't exist in memcached the error is ErrCacheMiss. The value in
|
||||
// memcached must be an decimal number, or an error will be returned.
|
||||
// On 64-bit overflow, the new value wraps around.
|
||||
func (c *Client) Increment(key string, delta uint64) (newValue uint64, err error) {
|
||||
return c.incrDecr("incr", key, delta)
|
||||
}
|
||||
|
||||
// Decrement atomically decrements key by delta. The return value is
|
||||
// the new value after being decremented or an error. If the value
|
||||
// didn't exist in memcached the error is ErrCacheMiss. The value in
|
||||
// memcached must be an decimal number, or an error will be returned.
|
||||
// On underflow, the new value is capped at zero and does not wrap
|
||||
// around.
|
||||
func (c *Client) Decrement(key string, delta uint64) (newValue uint64, err error) {
|
||||
return c.incrDecr("decr", key, delta)
|
||||
}
|
||||
|
||||
func (c *Client) incrDecr(verb, key string, delta uint64) (uint64, error) {
|
||||
var val uint64
|
||||
err := c.withKeyRw(key, func(rw *bufio.ReadWriter) error {
|
||||
line, err := writeReadLine(rw, "%s %s %d\r\n", verb, key, delta)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch {
|
||||
case bytes.Equal(line, resultNotFound):
|
||||
return ErrCacheMiss
|
||||
case bytes.HasPrefix(line, resultClientErrorPrefix):
|
||||
errMsg := line[len(resultClientErrorPrefix) : len(line)-2]
|
||||
return errors.New("memcache: client error: " + string(errMsg))
|
||||
}
|
||||
val, err = strconv.ParseUint(string(line[:len(line)-2]), 10, 64)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return val, err
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
Copyright 2011 Google Inc.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
*/
|
||||
|
||||
package memcache
|
||||
|
||||
import (
|
||||
"hash/crc32"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ServerSelector is the interface that selects a memcache server
|
||||
// as a function of the item's key.
|
||||
//
|
||||
// All ServerSelector implementations must be safe for concurrent use
|
||||
// by multiple goroutines.
|
||||
type ServerSelector interface {
|
||||
// PickServer returns the server address that a given item
|
||||
// should be shared onto.
|
||||
PickServer(key string) (net.Addr, error)
|
||||
Each(func(net.Addr) error) error
|
||||
}
|
||||
|
||||
// ServerList is a simple ServerSelector. Its zero value is usable.
|
||||
type ServerList struct {
|
||||
mu sync.RWMutex
|
||||
addrs []net.Addr
|
||||
}
|
||||
|
||||
// staticAddr caches the Network() and String() values from any net.Addr.
|
||||
type staticAddr struct {
|
||||
ntw, str string
|
||||
}
|
||||
|
||||
func newStaticAddr(a net.Addr) net.Addr {
|
||||
return &staticAddr{
|
||||
ntw: a.Network(),
|
||||
str: a.String(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *staticAddr) Network() string { return s.ntw }
|
||||
func (s *staticAddr) String() string { return s.str }
|
||||
|
||||
// SetServers changes a ServerList's set of servers at runtime and is
|
||||
// safe for concurrent use by multiple goroutines.
|
||||
//
|
||||
// Each server is given equal weight. A server is given more weight
|
||||
// if it's listed multiple times.
|
||||
//
|
||||
// SetServers returns an error if any of the server names fail to
|
||||
// resolve. No attempt is made to connect to the server. If any error
|
||||
// is returned, no changes are made to the ServerList.
|
||||
func (ss *ServerList) SetServers(servers ...string) error {
|
||||
naddr := make([]net.Addr, len(servers))
|
||||
for i, server := range servers {
|
||||
if strings.Contains(server, "/") {
|
||||
addr, err := net.ResolveUnixAddr("unix", server)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
naddr[i] = newStaticAddr(addr)
|
||||
} else {
|
||||
tcpaddr, err := net.ResolveTCPAddr("tcp", server)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
naddr[i] = newStaticAddr(tcpaddr)
|
||||
}
|
||||
}
|
||||
|
||||
ss.mu.Lock()
|
||||
defer ss.mu.Unlock()
|
||||
ss.addrs = naddr
|
||||
return nil
|
||||
}
|
||||
|
||||
// Each iterates over each server calling the given function
|
||||
func (ss *ServerList) Each(f func(net.Addr) error) error {
|
||||
ss.mu.RLock()
|
||||
defer ss.mu.RUnlock()
|
||||
for _, a := range ss.addrs {
|
||||
if err := f(a); nil != err {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// keyBufPool returns []byte buffers for use by PickServer's call to
|
||||
// crc32.ChecksumIEEE to avoid allocations. (but doesn't avoid the
|
||||
// copies, which at least are bounded in size and small)
|
||||
var keyBufPool = sync.Pool{
|
||||
New: func() interface{} {
|
||||
b := make([]byte, 256)
|
||||
return &b
|
||||
},
|
||||
}
|
||||
|
||||
func (ss *ServerList) PickServer(key string) (net.Addr, error) {
|
||||
ss.mu.RLock()
|
||||
defer ss.mu.RUnlock()
|
||||
if len(ss.addrs) == 0 {
|
||||
return nil, ErrNoServers
|
||||
}
|
||||
if len(ss.addrs) == 1 {
|
||||
return ss.addrs[0], nil
|
||||
}
|
||||
bufp := keyBufPool.Get().(*[]byte)
|
||||
n := copy(*bufp, key)
|
||||
cs := crc32.ChecksumIEEE((*bufp)[:n])
|
||||
keyBufPool.Put(bufp)
|
||||
|
||||
return ss.addrs[cs%uint32(len(ss.addrs))], nil
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- tip
|
||||
sudo: false
|
||||
before_install:
|
||||
- go get github.com/axw/gocov/gocov
|
||||
- go get github.com/mattn/goveralls
|
||||
- if ! go get github.com/golang/tools/cmd/cover; then go get golang.org/x/tools/cmd/cover; fi
|
||||
script:
|
||||
- $HOME/gopath/bin/goveralls -service=travis-ci
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Fatih Arslan
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
# Structs [](http://godoc.org/github.com/fatih/structs) [](https://travis-ci.org/fatih/structs) [](https://coveralls.io/r/fatih/structs)
|
||||
|
||||
Structs contains various utilities to work with Go (Golang) structs. It was
|
||||
initially used by me to convert a struct into a `map[string]interface{}`. With
|
||||
time I've added other utilities for structs. It's basically a high level
|
||||
package based on primitives from the reflect package. Feel free to add new
|
||||
functions or improve the existing code.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
go get github.com/fatih/structs
|
||||
```
|
||||
|
||||
## Usage and Examples
|
||||
|
||||
Just like the standard lib `strings`, `bytes` and co packages, `structs` has
|
||||
many global functions to manipulate or organize your struct data. Lets define
|
||||
and declare a struct:
|
||||
|
||||
```go
|
||||
type Server struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
ID int
|
||||
Enabled bool
|
||||
users []string // not exported
|
||||
http.Server // embedded
|
||||
}
|
||||
|
||||
server := &Server{
|
||||
Name: "gopher",
|
||||
ID: 123456,
|
||||
Enabled: true,
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
// Convert a struct to a map[string]interface{}
|
||||
// => {"Name":"gopher", "ID":123456, "Enabled":true}
|
||||
m := structs.Map(server)
|
||||
|
||||
// Convert the values of a struct to a []interface{}
|
||||
// => ["gopher", 123456, true]
|
||||
v := structs.Values(server)
|
||||
|
||||
// Convert the names of a struct to a []string
|
||||
// (see "Names methods" for more info about fields)
|
||||
n := structs.Names(server)
|
||||
|
||||
// Convert the values of a struct to a []*Field
|
||||
// (see "Field methods" for more info about fields)
|
||||
f := structs.Fields(server)
|
||||
|
||||
// Return the struct name => "Server"
|
||||
n := structs.Name(server)
|
||||
|
||||
// Check if any field of a struct is initialized or not.
|
||||
h := structs.HasZero(server)
|
||||
|
||||
// Check if all fields of a struct is initialized or not.
|
||||
z := structs.IsZero(server)
|
||||
|
||||
// Check if server is a struct or a pointer to struct
|
||||
i := structs.IsStruct(server)
|
||||
```
|
||||
|
||||
### Struct methods
|
||||
|
||||
The structs functions can be also used as independent methods by creating a new
|
||||
`*structs.Struct`. This is handy if you want to have more control over the
|
||||
structs (such as retrieving a single Field).
|
||||
|
||||
```go
|
||||
// Create a new struct type:
|
||||
s := structs.New(server)
|
||||
|
||||
m := s.Map() // Get a map[string]interface{}
|
||||
v := s.Values() // Get a []interface{}
|
||||
f := s.Fields() // Get a []*Field
|
||||
n := s.Names() // Get a []string
|
||||
f := s.Field(name) // Get a *Field based on the given field name
|
||||
f, ok := s.FieldOk(name) // Get a *Field based on the given field name
|
||||
n := s.Name() // Get the struct name
|
||||
h := s.HasZero() // Check if any field is uninitialized
|
||||
z := s.IsZero() // Check if all fields are uninitialized
|
||||
```
|
||||
|
||||
### Field methods
|
||||
|
||||
We can easily examine a single Field for more detail. Below you can see how we
|
||||
get and interact with various field methods:
|
||||
|
||||
|
||||
```go
|
||||
s := structs.New(server)
|
||||
|
||||
// Get the Field struct for the "Name" field
|
||||
name := s.Field("Name")
|
||||
|
||||
// Get the underlying value, value => "gopher"
|
||||
value := name.Value().(string)
|
||||
|
||||
// Set the field's value
|
||||
name.Set("another gopher")
|
||||
|
||||
// Get the field's kind, kind => "string"
|
||||
name.Kind()
|
||||
|
||||
// Check if the field is exported or not
|
||||
if name.IsExported() {
|
||||
fmt.Println("Name field is exported")
|
||||
}
|
||||
|
||||
// Check if the value is a zero value, such as "" for string, 0 for int
|
||||
if !name.IsZero() {
|
||||
fmt.Println("Name is initialized")
|
||||
}
|
||||
|
||||
// Check if the field is an anonymous (embedded) field
|
||||
if !name.IsEmbedded() {
|
||||
fmt.Println("Name is not an embedded field")
|
||||
}
|
||||
|
||||
// Get the Field's tag value for tag name "json", tag value => "name,omitempty"
|
||||
tagValue := name.Tag("json")
|
||||
```
|
||||
|
||||
Nested structs are supported too:
|
||||
|
||||
```go
|
||||
addrField := s.Field("Server").Field("Addr")
|
||||
|
||||
// Get the value for addr
|
||||
a := addrField.Value().(string)
|
||||
|
||||
// Or get all fields
|
||||
httpServer := s.Field("Server").Fields()
|
||||
```
|
||||
|
||||
We can also get a slice of Fields from the Struct type to iterate over all
|
||||
fields. This is handy if you wish to examine all fields:
|
||||
|
||||
```go
|
||||
s := structs.New(server)
|
||||
|
||||
for _, f := range s.Fields() {
|
||||
fmt.Printf("field name: %+v\n", f.Name())
|
||||
|
||||
if f.IsExported() {
|
||||
fmt.Printf("value : %+v\n", f.Value())
|
||||
fmt.Printf("is zero : %+v\n", f.IsZero())
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Credits
|
||||
|
||||
* [Fatih Arslan](https://github.com/fatih)
|
||||
* [Cihangir Savas](https://github.com/cihangir)
|
||||
|
||||
## License
|
||||
|
||||
The MIT License (MIT) - see LICENSE.md for more details
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
package structs
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
var (
|
||||
errNotExported = errors.New("field is not exported")
|
||||
errNotSettable = errors.New("field is not settable")
|
||||
)
|
||||
|
||||
// Field represents a single struct field that encapsulates high level
|
||||
// functions around the field.
|
||||
type Field struct {
|
||||
value reflect.Value
|
||||
field reflect.StructField
|
||||
defaultTag string
|
||||
}
|
||||
|
||||
// Tag returns the value associated with key in the tag string. If there is no
|
||||
// such key in the tag, Tag returns the empty string.
|
||||
func (f *Field) Tag(key string) string {
|
||||
return f.field.Tag.Get(key)
|
||||
}
|
||||
|
||||
// Value returns the underlying value of the field. It panics if the field
|
||||
// is not exported.
|
||||
func (f *Field) Value() interface{} {
|
||||
return f.value.Interface()
|
||||
}
|
||||
|
||||
// IsEmbedded returns true if the given field is an anonymous field (embedded)
|
||||
func (f *Field) IsEmbedded() bool {
|
||||
return f.field.Anonymous
|
||||
}
|
||||
|
||||
// IsExported returns true if the given field is exported.
|
||||
func (f *Field) IsExported() bool {
|
||||
return f.field.PkgPath == ""
|
||||
}
|
||||
|
||||
// IsZero returns true if the given field is not initialized (has a zero value).
|
||||
// It panics if the field is not exported.
|
||||
func (f *Field) IsZero() bool {
|
||||
zero := reflect.Zero(f.value.Type()).Interface()
|
||||
current := f.Value()
|
||||
|
||||
return reflect.DeepEqual(current, zero)
|
||||
}
|
||||
|
||||
// Name returns the name of the given field
|
||||
func (f *Field) Name() string {
|
||||
return f.field.Name
|
||||
}
|
||||
|
||||
// Kind returns the fields kind, such as "string", "map", "bool", etc ..
|
||||
func (f *Field) Kind() reflect.Kind {
|
||||
return f.value.Kind()
|
||||
}
|
||||
|
||||
// Set sets the field to given value v. It returns an error if the field is not
|
||||
// settable (not addressable or not exported) or if the given value's type
|
||||
// doesn't match the fields type.
|
||||
func (f *Field) Set(val interface{}) error {
|
||||
// we can't set unexported fields, so be sure this field is exported
|
||||
if !f.IsExported() {
|
||||
return errNotExported
|
||||
}
|
||||
|
||||
// do we get here? not sure...
|
||||
if !f.value.CanSet() {
|
||||
return errNotSettable
|
||||
}
|
||||
|
||||
given := reflect.ValueOf(val)
|
||||
|
||||
if f.value.Kind() != given.Kind() {
|
||||
return fmt.Errorf("wrong kind. got: %s want: %s", given.Kind(), f.value.Kind())
|
||||
}
|
||||
|
||||
f.value.Set(given)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Zero sets the field to its zero value. It returns an error if the field is not
|
||||
// settable (not addressable or not exported).
|
||||
func (f *Field) Zero() error {
|
||||
zero := reflect.Zero(f.value.Type()).Interface()
|
||||
return f.Set(zero)
|
||||
}
|
||||
|
||||
// Fields returns a slice of Fields. This is particular handy to get the fields
|
||||
// of a nested struct . A struct tag with the content of "-" ignores the
|
||||
// checking of that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field *http.Request `structs:"-"`
|
||||
//
|
||||
// It panics if field is not exported or if field's kind is not struct
|
||||
func (f *Field) Fields() []*Field {
|
||||
return getFields(f.value, f.defaultTag)
|
||||
}
|
||||
|
||||
// Field returns the field from a nested struct. It panics if the nested struct
|
||||
// is not exported or if the field was not found.
|
||||
func (f *Field) Field(name string) *Field {
|
||||
field, ok := f.FieldOk(name)
|
||||
if !ok {
|
||||
panic("field not found")
|
||||
}
|
||||
|
||||
return field
|
||||
}
|
||||
|
||||
// FieldOk returns the field from a nested struct. The boolean returns whether
|
||||
// the field was found (true) or not (false).
|
||||
func (f *Field) FieldOk(name string) (*Field, bool) {
|
||||
value := &f.value
|
||||
// value must be settable so we need to make sure it holds the address of the
|
||||
// variable and not a copy, so we can pass the pointer to strctVal instead of a
|
||||
// copy (which is not assigned to any variable, hence not settable).
|
||||
// see "https://blog.golang.org/laws-of-reflection#TOC_8."
|
||||
if f.value.Kind() != reflect.Ptr {
|
||||
a := f.value.Addr()
|
||||
value = &a
|
||||
}
|
||||
v := strctVal(value.Interface())
|
||||
t := v.Type()
|
||||
|
||||
field, ok := t.FieldByName(name)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &Field{
|
||||
field: field,
|
||||
value: v.FieldByName(name),
|
||||
}, true
|
||||
}
|
||||
+584
@@ -0,0 +1,584 @@
|
||||
// Package structs contains various utilities functions to work with structs.
|
||||
package structs
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"reflect"
|
||||
)
|
||||
|
||||
var (
|
||||
// DefaultTagName is the default tag name for struct fields which provides
|
||||
// a more granular to tweak certain structs. Lookup the necessary functions
|
||||
// for more info.
|
||||
DefaultTagName = "structs" // struct's field default tag name
|
||||
)
|
||||
|
||||
// Struct encapsulates a struct type to provide several high level functions
|
||||
// around the struct.
|
||||
type Struct struct {
|
||||
raw interface{}
|
||||
value reflect.Value
|
||||
TagName string
|
||||
}
|
||||
|
||||
// New returns a new *Struct with the struct s. It panics if the s's kind is
|
||||
// not struct.
|
||||
func New(s interface{}) *Struct {
|
||||
return &Struct{
|
||||
raw: s,
|
||||
value: strctVal(s),
|
||||
TagName: DefaultTagName,
|
||||
}
|
||||
}
|
||||
|
||||
// Map converts the given struct to a map[string]interface{}, where the keys
|
||||
// of the map are the field names and the values of the map the associated
|
||||
// values of the fields. The default key string is the struct field name but
|
||||
// can be changed in the struct field's tag value. The "structs" key in the
|
||||
// struct's field tag value is the key name. Example:
|
||||
//
|
||||
// // Field appears in map as key "myName".
|
||||
// Name string `structs:"myName"`
|
||||
//
|
||||
// A tag value with the content of "-" ignores that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// A tag value with the content of "string" uses the stringer to get the value. Example:
|
||||
//
|
||||
// // The value will be output of Animal's String() func.
|
||||
// // Map will panic if Animal does not implement String().
|
||||
// Field *Animal `structs:"field,string"`
|
||||
//
|
||||
// A tag value with the option of "flatten" used in a struct field is to flatten its fields
|
||||
// in the output map. Example:
|
||||
//
|
||||
// // The FieldStruct's fields will be flattened into the output map.
|
||||
// FieldStruct time.Time `structs:",flatten"`
|
||||
//
|
||||
// A tag value with the option of "omitnested" stops iterating further if the type
|
||||
// is a struct. Example:
|
||||
//
|
||||
// // Field is not processed further by this package.
|
||||
// Field time.Time `structs:"myName,omitnested"`
|
||||
// Field *http.Request `structs:",omitnested"`
|
||||
//
|
||||
// A tag value with the option of "omitempty" ignores that particular field if
|
||||
// the field value is empty. Example:
|
||||
//
|
||||
// // Field appears in map as key "myName", but the field is
|
||||
// // skipped if empty.
|
||||
// Field string `structs:"myName,omitempty"`
|
||||
//
|
||||
// // Field appears in map as key "Field" (the default), but
|
||||
// // the field is skipped if empty.
|
||||
// Field string `structs:",omitempty"`
|
||||
//
|
||||
// Note that only exported fields of a struct can be accessed, non exported
|
||||
// fields will be neglected.
|
||||
func (s *Struct) Map() map[string]interface{} {
|
||||
out := make(map[string]interface{})
|
||||
s.FillMap(out)
|
||||
return out
|
||||
}
|
||||
|
||||
// FillMap is the same as Map. Instead of returning the output, it fills the
|
||||
// given map.
|
||||
func (s *Struct) FillMap(out map[string]interface{}) {
|
||||
if out == nil {
|
||||
return
|
||||
}
|
||||
|
||||
fields := s.structFields()
|
||||
|
||||
for _, field := range fields {
|
||||
name := field.Name
|
||||
val := s.value.FieldByName(name)
|
||||
isSubStruct := false
|
||||
var finalVal interface{}
|
||||
|
||||
tagName, tagOpts := parseTag(field.Tag.Get(s.TagName))
|
||||
if tagName != "" {
|
||||
name = tagName
|
||||
}
|
||||
|
||||
// if the value is a zero value and the field is marked as omitempty do
|
||||
// not include
|
||||
if tagOpts.Has("omitempty") {
|
||||
zero := reflect.Zero(val.Type()).Interface()
|
||||
current := val.Interface()
|
||||
|
||||
if reflect.DeepEqual(current, zero) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if !tagOpts.Has("omitnested") {
|
||||
finalVal = s.nested(val)
|
||||
|
||||
v := reflect.ValueOf(val.Interface())
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
switch v.Kind() {
|
||||
case reflect.Map, reflect.Struct:
|
||||
isSubStruct = true
|
||||
}
|
||||
} else {
|
||||
finalVal = val.Interface()
|
||||
}
|
||||
|
||||
if tagOpts.Has("string") {
|
||||
s, ok := val.Interface().(fmt.Stringer)
|
||||
if ok {
|
||||
out[name] = s.String()
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if isSubStruct && (tagOpts.Has("flatten")) {
|
||||
for k := range finalVal.(map[string]interface{}) {
|
||||
out[k] = finalVal.(map[string]interface{})[k]
|
||||
}
|
||||
} else {
|
||||
out[name] = finalVal
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Values converts the given s struct's field values to a []interface{}. A
|
||||
// struct tag with the content of "-" ignores the that particular field.
|
||||
// Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field int `structs:"-"`
|
||||
//
|
||||
// A value with the option of "omitnested" stops iterating further if the type
|
||||
// is a struct. Example:
|
||||
//
|
||||
// // Fields is not processed further by this package.
|
||||
// Field time.Time `structs:",omitnested"`
|
||||
// Field *http.Request `structs:",omitnested"`
|
||||
//
|
||||
// A tag value with the option of "omitempty" ignores that particular field and
|
||||
// is not added to the values if the field value is empty. Example:
|
||||
//
|
||||
// // Field is skipped if empty
|
||||
// Field string `structs:",omitempty"`
|
||||
//
|
||||
// Note that only exported fields of a struct can be accessed, non exported
|
||||
// fields will be neglected.
|
||||
func (s *Struct) Values() []interface{} {
|
||||
fields := s.structFields()
|
||||
|
||||
var t []interface{}
|
||||
|
||||
for _, field := range fields {
|
||||
val := s.value.FieldByName(field.Name)
|
||||
|
||||
_, tagOpts := parseTag(field.Tag.Get(s.TagName))
|
||||
|
||||
// if the value is a zero value and the field is marked as omitempty do
|
||||
// not include
|
||||
if tagOpts.Has("omitempty") {
|
||||
zero := reflect.Zero(val.Type()).Interface()
|
||||
current := val.Interface()
|
||||
|
||||
if reflect.DeepEqual(current, zero) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
if tagOpts.Has("string") {
|
||||
s, ok := val.Interface().(fmt.Stringer)
|
||||
if ok {
|
||||
t = append(t, s.String())
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") {
|
||||
// look out for embedded structs, and convert them to a
|
||||
// []interface{} to be added to the final values slice
|
||||
t = append(t, Values(val.Interface())...)
|
||||
} else {
|
||||
t = append(t, val.Interface())
|
||||
}
|
||||
}
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
// Fields returns a slice of Fields. A struct tag with the content of "-"
|
||||
// ignores the checking of that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// It panics if s's kind is not struct.
|
||||
func (s *Struct) Fields() []*Field {
|
||||
return getFields(s.value, s.TagName)
|
||||
}
|
||||
|
||||
// Names returns a slice of field names. A struct tag with the content of "-"
|
||||
// ignores the checking of that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// It panics if s's kind is not struct.
|
||||
func (s *Struct) Names() []string {
|
||||
fields := getFields(s.value, s.TagName)
|
||||
|
||||
names := make([]string, len(fields))
|
||||
|
||||
for i, field := range fields {
|
||||
names[i] = field.Name()
|
||||
}
|
||||
|
||||
return names
|
||||
}
|
||||
|
||||
func getFields(v reflect.Value, tagName string) []*Field {
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
t := v.Type()
|
||||
|
||||
var fields []*Field
|
||||
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
field := t.Field(i)
|
||||
|
||||
if tag := field.Tag.Get(tagName); tag == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
f := &Field{
|
||||
field: field,
|
||||
value: v.FieldByName(field.Name),
|
||||
}
|
||||
|
||||
fields = append(fields, f)
|
||||
|
||||
}
|
||||
|
||||
return fields
|
||||
}
|
||||
|
||||
// Field returns a new Field struct that provides several high level functions
|
||||
// around a single struct field entity. It panics if the field is not found.
|
||||
func (s *Struct) Field(name string) *Field {
|
||||
f, ok := s.FieldOk(name)
|
||||
if !ok {
|
||||
panic("field not found")
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
// FieldOk returns a new Field struct that provides several high level functions
|
||||
// around a single struct field entity. The boolean returns true if the field
|
||||
// was found.
|
||||
func (s *Struct) FieldOk(name string) (*Field, bool) {
|
||||
t := s.value.Type()
|
||||
|
||||
field, ok := t.FieldByName(name)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &Field{
|
||||
field: field,
|
||||
value: s.value.FieldByName(name),
|
||||
defaultTag: s.TagName,
|
||||
}, true
|
||||
}
|
||||
|
||||
// IsZero returns true if all fields in a struct is a zero value (not
|
||||
// initialized) A struct tag with the content of "-" ignores the checking of
|
||||
// that particular field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// A value with the option of "omitnested" stops iterating further if the type
|
||||
// is a struct. Example:
|
||||
//
|
||||
// // Field is not processed further by this package.
|
||||
// Field time.Time `structs:"myName,omitnested"`
|
||||
// Field *http.Request `structs:",omitnested"`
|
||||
//
|
||||
// Note that only exported fields of a struct can be accessed, non exported
|
||||
// fields will be neglected. It panics if s's kind is not struct.
|
||||
func (s *Struct) IsZero() bool {
|
||||
fields := s.structFields()
|
||||
|
||||
for _, field := range fields {
|
||||
val := s.value.FieldByName(field.Name)
|
||||
|
||||
_, tagOpts := parseTag(field.Tag.Get(s.TagName))
|
||||
|
||||
if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") {
|
||||
ok := IsZero(val.Interface())
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// zero value of the given field, such as "" for string, 0 for int
|
||||
zero := reflect.Zero(val.Type()).Interface()
|
||||
|
||||
// current value of the given field
|
||||
current := val.Interface()
|
||||
|
||||
if !reflect.DeepEqual(current, zero) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// HasZero returns true if a field in a struct is not initialized (zero value).
|
||||
// A struct tag with the content of "-" ignores the checking of that particular
|
||||
// field. Example:
|
||||
//
|
||||
// // Field is ignored by this package.
|
||||
// Field bool `structs:"-"`
|
||||
//
|
||||
// A value with the option of "omitnested" stops iterating further if the type
|
||||
// is a struct. Example:
|
||||
//
|
||||
// // Field is not processed further by this package.
|
||||
// Field time.Time `structs:"myName,omitnested"`
|
||||
// Field *http.Request `structs:",omitnested"`
|
||||
//
|
||||
// Note that only exported fields of a struct can be accessed, non exported
|
||||
// fields will be neglected. It panics if s's kind is not struct.
|
||||
func (s *Struct) HasZero() bool {
|
||||
fields := s.structFields()
|
||||
|
||||
for _, field := range fields {
|
||||
val := s.value.FieldByName(field.Name)
|
||||
|
||||
_, tagOpts := parseTag(field.Tag.Get(s.TagName))
|
||||
|
||||
if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") {
|
||||
ok := HasZero(val.Interface())
|
||||
if ok {
|
||||
return true
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
// zero value of the given field, such as "" for string, 0 for int
|
||||
zero := reflect.Zero(val.Type()).Interface()
|
||||
|
||||
// current value of the given field
|
||||
current := val.Interface()
|
||||
|
||||
if reflect.DeepEqual(current, zero) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// Name returns the structs's type name within its package. For more info refer
|
||||
// to Name() function.
|
||||
func (s *Struct) Name() string {
|
||||
return s.value.Type().Name()
|
||||
}
|
||||
|
||||
// structFields returns the exported struct fields for a given s struct. This
|
||||
// is a convenient helper method to avoid duplicate code in some of the
|
||||
// functions.
|
||||
func (s *Struct) structFields() []reflect.StructField {
|
||||
t := s.value.Type()
|
||||
|
||||
var f []reflect.StructField
|
||||
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
field := t.Field(i)
|
||||
// we can't access the value of unexported fields
|
||||
if field.PkgPath != "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// don't check if it's omitted
|
||||
if tag := field.Tag.Get(s.TagName); tag == "-" {
|
||||
continue
|
||||
}
|
||||
|
||||
f = append(f, field)
|
||||
}
|
||||
|
||||
return f
|
||||
}
|
||||
|
||||
func strctVal(s interface{}) reflect.Value {
|
||||
v := reflect.ValueOf(s)
|
||||
|
||||
// if pointer get the underlying element≤
|
||||
for v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
if v.Kind() != reflect.Struct {
|
||||
panic("not struct")
|
||||
}
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
// Map converts the given struct to a map[string]interface{}. For more info
|
||||
// refer to Struct types Map() method. It panics if s's kind is not struct.
|
||||
func Map(s interface{}) map[string]interface{} {
|
||||
return New(s).Map()
|
||||
}
|
||||
|
||||
// FillMap is the same as Map. Instead of returning the output, it fills the
|
||||
// given map.
|
||||
func FillMap(s interface{}, out map[string]interface{}) {
|
||||
New(s).FillMap(out)
|
||||
}
|
||||
|
||||
// Values converts the given struct to a []interface{}. For more info refer to
|
||||
// Struct types Values() method. It panics if s's kind is not struct.
|
||||
func Values(s interface{}) []interface{} {
|
||||
return New(s).Values()
|
||||
}
|
||||
|
||||
// Fields returns a slice of *Field. For more info refer to Struct types
|
||||
// Fields() method. It panics if s's kind is not struct.
|
||||
func Fields(s interface{}) []*Field {
|
||||
return New(s).Fields()
|
||||
}
|
||||
|
||||
// Names returns a slice of field names. For more info refer to Struct types
|
||||
// Names() method. It panics if s's kind is not struct.
|
||||
func Names(s interface{}) []string {
|
||||
return New(s).Names()
|
||||
}
|
||||
|
||||
// IsZero returns true if all fields is equal to a zero value. For more info
|
||||
// refer to Struct types IsZero() method. It panics if s's kind is not struct.
|
||||
func IsZero(s interface{}) bool {
|
||||
return New(s).IsZero()
|
||||
}
|
||||
|
||||
// HasZero returns true if any field is equal to a zero value. For more info
|
||||
// refer to Struct types HasZero() method. It panics if s's kind is not struct.
|
||||
func HasZero(s interface{}) bool {
|
||||
return New(s).HasZero()
|
||||
}
|
||||
|
||||
// IsStruct returns true if the given variable is a struct or a pointer to
|
||||
// struct.
|
||||
func IsStruct(s interface{}) bool {
|
||||
v := reflect.ValueOf(s)
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
// uninitialized zero value of a struct
|
||||
if v.Kind() == reflect.Invalid {
|
||||
return false
|
||||
}
|
||||
|
||||
return v.Kind() == reflect.Struct
|
||||
}
|
||||
|
||||
// Name returns the structs's type name within its package. It returns an
|
||||
// empty string for unnamed types. It panics if s's kind is not struct.
|
||||
func Name(s interface{}) string {
|
||||
return New(s).Name()
|
||||
}
|
||||
|
||||
// nested retrieves recursively all types for the given value and returns the
|
||||
// nested value.
|
||||
func (s *Struct) nested(val reflect.Value) interface{} {
|
||||
var finalVal interface{}
|
||||
|
||||
v := reflect.ValueOf(val.Interface())
|
||||
if v.Kind() == reflect.Ptr {
|
||||
v = v.Elem()
|
||||
}
|
||||
|
||||
switch v.Kind() {
|
||||
case reflect.Struct:
|
||||
n := New(val.Interface())
|
||||
n.TagName = s.TagName
|
||||
m := n.Map()
|
||||
|
||||
// do not add the converted value if there are no exported fields, ie:
|
||||
// time.Time
|
||||
if len(m) == 0 {
|
||||
finalVal = val.Interface()
|
||||
} else {
|
||||
finalVal = m
|
||||
}
|
||||
case reflect.Map:
|
||||
// get the element type of the map
|
||||
mapElem := val.Type()
|
||||
switch val.Type().Kind() {
|
||||
case reflect.Ptr, reflect.Array, reflect.Map,
|
||||
reflect.Slice, reflect.Chan:
|
||||
mapElem = val.Type().Elem()
|
||||
if mapElem.Kind() == reflect.Ptr {
|
||||
mapElem = mapElem.Elem()
|
||||
}
|
||||
}
|
||||
|
||||
// only iterate over struct types, ie: map[string]StructType,
|
||||
// map[string][]StructType,
|
||||
if mapElem.Kind() == reflect.Struct ||
|
||||
(mapElem.Kind() == reflect.Slice &&
|
||||
mapElem.Elem().Kind() == reflect.Struct) {
|
||||
m := make(map[string]interface{}, val.Len())
|
||||
for _, k := range val.MapKeys() {
|
||||
m[k.String()] = s.nested(val.MapIndex(k))
|
||||
}
|
||||
finalVal = m
|
||||
break
|
||||
}
|
||||
|
||||
// TODO(arslan): should this be optional?
|
||||
finalVal = val.Interface()
|
||||
case reflect.Slice, reflect.Array:
|
||||
if val.Type().Kind() == reflect.Interface {
|
||||
finalVal = val.Interface()
|
||||
break
|
||||
}
|
||||
|
||||
// TODO(arslan): should this be optional?
|
||||
// do not iterate of non struct types, just pass the value. Ie: []int,
|
||||
// []string, co... We only iterate further if it's a struct.
|
||||
// i.e []foo or []*foo
|
||||
if val.Type().Elem().Kind() != reflect.Struct &&
|
||||
!(val.Type().Elem().Kind() == reflect.Ptr &&
|
||||
val.Type().Elem().Elem().Kind() == reflect.Struct) {
|
||||
finalVal = val.Interface()
|
||||
break
|
||||
}
|
||||
|
||||
slices := make([]interface{}, val.Len())
|
||||
for x := 0; x < val.Len(); x++ {
|
||||
slices[x] = s.nested(val.Index(x))
|
||||
}
|
||||
finalVal = slices
|
||||
default:
|
||||
finalVal = val.Interface()
|
||||
}
|
||||
|
||||
return finalVal
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package structs
|
||||
|
||||
import "strings"
|
||||
|
||||
// tagOptions contains a slice of tag options
|
||||
type tagOptions []string
|
||||
|
||||
// Has returns true if the given option is available in tagOptions
|
||||
func (t tagOptions) Has(opt string) bool {
|
||||
for _, tagOpt := range t {
|
||||
if tagOpt == opt {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// parseTag splits a struct field's tag into its name and a list of options
|
||||
// which comes after a name. A tag is in the form of: "name,option1,option2".
|
||||
// The name can be neglectected.
|
||||
func parseTag(tag string) (string, tagOptions) {
|
||||
// tag is one of followings:
|
||||
// ""
|
||||
// "name"
|
||||
// "name,opt"
|
||||
// "name,opt,opt2"
|
||||
// ",opt"
|
||||
|
||||
res := strings.Split(tag, ",")
|
||||
return res[0], res[1:]
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
// Copyright 2014 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package internal // import "github.com/garyburd/redigo/internal"
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
WatchState = 1 << iota
|
||||
MultiState
|
||||
SubscribeState
|
||||
MonitorState
|
||||
)
|
||||
|
||||
type CommandInfo struct {
|
||||
Set, Clear int
|
||||
}
|
||||
|
||||
var commandInfos = map[string]CommandInfo{
|
||||
"WATCH": {Set: WatchState},
|
||||
"UNWATCH": {Clear: WatchState},
|
||||
"MULTI": {Set: MultiState},
|
||||
"EXEC": {Clear: WatchState | MultiState},
|
||||
"DISCARD": {Clear: WatchState | MultiState},
|
||||
"PSUBSCRIBE": {Set: SubscribeState},
|
||||
"SUBSCRIBE": {Set: SubscribeState},
|
||||
"MONITOR": {Set: MonitorState},
|
||||
}
|
||||
|
||||
func init() {
|
||||
for n, ci := range commandInfos {
|
||||
commandInfos[strings.ToLower(n)] = ci
|
||||
}
|
||||
}
|
||||
|
||||
func LookupCommandInfo(commandName string) CommandInfo {
|
||||
if ci, ok := commandInfos[commandName]; ok {
|
||||
return ci
|
||||
}
|
||||
return commandInfos[strings.ToUpper(commandName)]
|
||||
}
|
||||
+673
@@ -0,0 +1,673 @@
|
||||
// Copyright 2012 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package redis
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
_ ConnWithTimeout = (*conn)(nil)
|
||||
)
|
||||
|
||||
// conn is the low-level implementation of Conn
|
||||
type conn struct {
|
||||
// Shared
|
||||
mu sync.Mutex
|
||||
pending int
|
||||
err error
|
||||
conn net.Conn
|
||||
|
||||
// Read
|
||||
readTimeout time.Duration
|
||||
br *bufio.Reader
|
||||
|
||||
// Write
|
||||
writeTimeout time.Duration
|
||||
bw *bufio.Writer
|
||||
|
||||
// Scratch space for formatting argument length.
|
||||
// '*' or '$', length, "\r\n"
|
||||
lenScratch [32]byte
|
||||
|
||||
// Scratch space for formatting integers and floats.
|
||||
numScratch [40]byte
|
||||
}
|
||||
|
||||
// DialTimeout acts like Dial but takes timeouts for establishing the
|
||||
// connection to the server, writing a command and reading a reply.
|
||||
//
|
||||
// Deprecated: Use Dial with options instead.
|
||||
func DialTimeout(network, address string, connectTimeout, readTimeout, writeTimeout time.Duration) (Conn, error) {
|
||||
return Dial(network, address,
|
||||
DialConnectTimeout(connectTimeout),
|
||||
DialReadTimeout(readTimeout),
|
||||
DialWriteTimeout(writeTimeout))
|
||||
}
|
||||
|
||||
// DialOption specifies an option for dialing a Redis server.
|
||||
type DialOption struct {
|
||||
f func(*dialOptions)
|
||||
}
|
||||
|
||||
type dialOptions struct {
|
||||
readTimeout time.Duration
|
||||
writeTimeout time.Duration
|
||||
dialer *net.Dialer
|
||||
dial func(network, addr string) (net.Conn, error)
|
||||
db int
|
||||
password string
|
||||
useTLS bool
|
||||
skipVerify bool
|
||||
tlsConfig *tls.Config
|
||||
}
|
||||
|
||||
// DialReadTimeout specifies the timeout for reading a single command reply.
|
||||
func DialReadTimeout(d time.Duration) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.readTimeout = d
|
||||
}}
|
||||
}
|
||||
|
||||
// DialWriteTimeout specifies the timeout for writing a single command.
|
||||
func DialWriteTimeout(d time.Duration) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.writeTimeout = d
|
||||
}}
|
||||
}
|
||||
|
||||
// DialConnectTimeout specifies the timeout for connecting to the Redis server when
|
||||
// no DialNetDial option is specified.
|
||||
func DialConnectTimeout(d time.Duration) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.dialer.Timeout = d
|
||||
}}
|
||||
}
|
||||
|
||||
// DialKeepAlive specifies the keep-alive period for TCP connections to the Redis server
|
||||
// when no DialNetDial option is specified.
|
||||
// If zero, keep-alives are not enabled. If no DialKeepAlive option is specified then
|
||||
// the default of 5 minutes is used to ensure that half-closed TCP sessions are detected.
|
||||
func DialKeepAlive(d time.Duration) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.dialer.KeepAlive = d
|
||||
}}
|
||||
}
|
||||
|
||||
// DialNetDial specifies a custom dial function for creating TCP
|
||||
// connections, otherwise a net.Dialer customized via the other options is used.
|
||||
// DialNetDial overrides DialConnectTimeout and DialKeepAlive.
|
||||
func DialNetDial(dial func(network, addr string) (net.Conn, error)) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.dial = dial
|
||||
}}
|
||||
}
|
||||
|
||||
// DialDatabase specifies the database to select when dialing a connection.
|
||||
func DialDatabase(db int) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.db = db
|
||||
}}
|
||||
}
|
||||
|
||||
// DialPassword specifies the password to use when connecting to
|
||||
// the Redis server.
|
||||
func DialPassword(password string) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.password = password
|
||||
}}
|
||||
}
|
||||
|
||||
// DialTLSConfig specifies the config to use when a TLS connection is dialed.
|
||||
// Has no effect when not dialing a TLS connection.
|
||||
func DialTLSConfig(c *tls.Config) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.tlsConfig = c
|
||||
}}
|
||||
}
|
||||
|
||||
// DialTLSSkipVerify disables server name verification when connecting over
|
||||
// TLS. Has no effect when not dialing a TLS connection.
|
||||
func DialTLSSkipVerify(skip bool) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.skipVerify = skip
|
||||
}}
|
||||
}
|
||||
|
||||
// DialUseTLS specifies whether TLS should be used when connecting to the
|
||||
// server. This option is ignore by DialURL.
|
||||
func DialUseTLS(useTLS bool) DialOption {
|
||||
return DialOption{func(do *dialOptions) {
|
||||
do.useTLS = useTLS
|
||||
}}
|
||||
}
|
||||
|
||||
// Dial connects to the Redis server at the given network and
|
||||
// address using the specified options.
|
||||
func Dial(network, address string, options ...DialOption) (Conn, error) {
|
||||
do := dialOptions{
|
||||
dialer: &net.Dialer{
|
||||
KeepAlive: time.Minute * 5,
|
||||
},
|
||||
}
|
||||
for _, option := range options {
|
||||
option.f(&do)
|
||||
}
|
||||
if do.dial == nil {
|
||||
do.dial = do.dialer.Dial
|
||||
}
|
||||
|
||||
netConn, err := do.dial(network, address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if do.useTLS {
|
||||
var tlsConfig *tls.Config
|
||||
if do.tlsConfig == nil {
|
||||
tlsConfig = &tls.Config{InsecureSkipVerify: do.skipVerify}
|
||||
} else {
|
||||
tlsConfig = cloneTLSConfig(do.tlsConfig)
|
||||
}
|
||||
if tlsConfig.ServerName == "" {
|
||||
host, _, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
netConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
tlsConfig.ServerName = host
|
||||
}
|
||||
|
||||
tlsConn := tls.Client(netConn, tlsConfig)
|
||||
if err := tlsConn.Handshake(); err != nil {
|
||||
netConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
netConn = tlsConn
|
||||
}
|
||||
|
||||
c := &conn{
|
||||
conn: netConn,
|
||||
bw: bufio.NewWriter(netConn),
|
||||
br: bufio.NewReader(netConn),
|
||||
readTimeout: do.readTimeout,
|
||||
writeTimeout: do.writeTimeout,
|
||||
}
|
||||
|
||||
if do.password != "" {
|
||||
if _, err := c.Do("AUTH", do.password); err != nil {
|
||||
netConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
if do.db != 0 {
|
||||
if _, err := c.Do("SELECT", do.db); err != nil {
|
||||
netConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return c, nil
|
||||
}
|
||||
|
||||
var pathDBRegexp = regexp.MustCompile(`/(\d*)\z`)
|
||||
|
||||
// DialURL connects to a Redis server at the given URL using the Redis
|
||||
// URI scheme. URLs should follow the draft IANA specification for the
|
||||
// scheme (https://www.iana.org/assignments/uri-schemes/prov/redis).
|
||||
func DialURL(rawurl string, options ...DialOption) (Conn, error) {
|
||||
u, err := url.Parse(rawurl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if u.Scheme != "redis" && u.Scheme != "rediss" {
|
||||
return nil, fmt.Errorf("invalid redis URL scheme: %s", u.Scheme)
|
||||
}
|
||||
|
||||
// As per the IANA draft spec, the host defaults to localhost and
|
||||
// the port defaults to 6379.
|
||||
host, port, err := net.SplitHostPort(u.Host)
|
||||
if err != nil {
|
||||
// assume port is missing
|
||||
host = u.Host
|
||||
port = "6379"
|
||||
}
|
||||
if host == "" {
|
||||
host = "localhost"
|
||||
}
|
||||
address := net.JoinHostPort(host, port)
|
||||
|
||||
if u.User != nil {
|
||||
password, isSet := u.User.Password()
|
||||
if isSet {
|
||||
options = append(options, DialPassword(password))
|
||||
}
|
||||
}
|
||||
|
||||
match := pathDBRegexp.FindStringSubmatch(u.Path)
|
||||
if len(match) == 2 {
|
||||
db := 0
|
||||
if len(match[1]) > 0 {
|
||||
db, err = strconv.Atoi(match[1])
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
|
||||
}
|
||||
}
|
||||
if db != 0 {
|
||||
options = append(options, DialDatabase(db))
|
||||
}
|
||||
} else if u.Path != "" {
|
||||
return nil, fmt.Errorf("invalid database: %s", u.Path[1:])
|
||||
}
|
||||
|
||||
options = append(options, DialUseTLS(u.Scheme == "rediss"))
|
||||
|
||||
return Dial("tcp", address, options...)
|
||||
}
|
||||
|
||||
// NewConn returns a new Redigo connection for the given net connection.
|
||||
func NewConn(netConn net.Conn, readTimeout, writeTimeout time.Duration) Conn {
|
||||
return &conn{
|
||||
conn: netConn,
|
||||
bw: bufio.NewWriter(netConn),
|
||||
br: bufio.NewReader(netConn),
|
||||
readTimeout: readTimeout,
|
||||
writeTimeout: writeTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *conn) Close() error {
|
||||
c.mu.Lock()
|
||||
err := c.err
|
||||
if c.err == nil {
|
||||
c.err = errors.New("redigo: closed")
|
||||
err = c.conn.Close()
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *conn) fatal(err error) error {
|
||||
c.mu.Lock()
|
||||
if c.err == nil {
|
||||
c.err = err
|
||||
// Close connection to force errors on subsequent calls and to unblock
|
||||
// other reader or writer.
|
||||
c.conn.Close()
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *conn) Err() error {
|
||||
c.mu.Lock()
|
||||
err := c.err
|
||||
c.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *conn) writeLen(prefix byte, n int) error {
|
||||
c.lenScratch[len(c.lenScratch)-1] = '\n'
|
||||
c.lenScratch[len(c.lenScratch)-2] = '\r'
|
||||
i := len(c.lenScratch) - 3
|
||||
for {
|
||||
c.lenScratch[i] = byte('0' + n%10)
|
||||
i -= 1
|
||||
n = n / 10
|
||||
if n == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
c.lenScratch[i] = prefix
|
||||
_, err := c.bw.Write(c.lenScratch[i:])
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *conn) writeString(s string) error {
|
||||
c.writeLen('$', len(s))
|
||||
c.bw.WriteString(s)
|
||||
_, err := c.bw.WriteString("\r\n")
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *conn) writeBytes(p []byte) error {
|
||||
c.writeLen('$', len(p))
|
||||
c.bw.Write(p)
|
||||
_, err := c.bw.WriteString("\r\n")
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *conn) writeInt64(n int64) error {
|
||||
return c.writeBytes(strconv.AppendInt(c.numScratch[:0], n, 10))
|
||||
}
|
||||
|
||||
func (c *conn) writeFloat64(n float64) error {
|
||||
return c.writeBytes(strconv.AppendFloat(c.numScratch[:0], n, 'g', -1, 64))
|
||||
}
|
||||
|
||||
func (c *conn) writeCommand(cmd string, args []interface{}) error {
|
||||
c.writeLen('*', 1+len(args))
|
||||
if err := c.writeString(cmd); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, arg := range args {
|
||||
if err := c.writeArg(arg, true); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *conn) writeArg(arg interface{}, argumentTypeOK bool) (err error) {
|
||||
switch arg := arg.(type) {
|
||||
case string:
|
||||
return c.writeString(arg)
|
||||
case []byte:
|
||||
return c.writeBytes(arg)
|
||||
case int:
|
||||
return c.writeInt64(int64(arg))
|
||||
case int64:
|
||||
return c.writeInt64(arg)
|
||||
case float64:
|
||||
return c.writeFloat64(arg)
|
||||
case bool:
|
||||
if arg {
|
||||
return c.writeString("1")
|
||||
} else {
|
||||
return c.writeString("0")
|
||||
}
|
||||
case nil:
|
||||
return c.writeString("")
|
||||
case Argument:
|
||||
if argumentTypeOK {
|
||||
return c.writeArg(arg.RedisArg(), false)
|
||||
}
|
||||
// See comment in default clause below.
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprint(&buf, arg)
|
||||
return c.writeBytes(buf.Bytes())
|
||||
default:
|
||||
// This default clause is intended to handle builtin numeric types.
|
||||
// The function should return an error for other types, but this is not
|
||||
// done for compatibility with previous versions of the package.
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprint(&buf, arg)
|
||||
return c.writeBytes(buf.Bytes())
|
||||
}
|
||||
}
|
||||
|
||||
type protocolError string
|
||||
|
||||
func (pe protocolError) Error() string {
|
||||
return fmt.Sprintf("redigo: %s (possible server error or unsupported concurrent read by application)", string(pe))
|
||||
}
|
||||
|
||||
func (c *conn) readLine() ([]byte, error) {
|
||||
p, err := c.br.ReadSlice('\n')
|
||||
if err == bufio.ErrBufferFull {
|
||||
return nil, protocolError("long response line")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
i := len(p) - 2
|
||||
if i < 0 || p[i] != '\r' {
|
||||
return nil, protocolError("bad response line terminator")
|
||||
}
|
||||
return p[:i], nil
|
||||
}
|
||||
|
||||
// parseLen parses bulk string and array lengths.
|
||||
func parseLen(p []byte) (int, error) {
|
||||
if len(p) == 0 {
|
||||
return -1, protocolError("malformed length")
|
||||
}
|
||||
|
||||
if p[0] == '-' && len(p) == 2 && p[1] == '1' {
|
||||
// handle $-1 and $-1 null replies.
|
||||
return -1, nil
|
||||
}
|
||||
|
||||
var n int
|
||||
for _, b := range p {
|
||||
n *= 10
|
||||
if b < '0' || b > '9' {
|
||||
return -1, protocolError("illegal bytes in length")
|
||||
}
|
||||
n += int(b - '0')
|
||||
}
|
||||
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// parseInt parses an integer reply.
|
||||
func parseInt(p []byte) (interface{}, error) {
|
||||
if len(p) == 0 {
|
||||
return 0, protocolError("malformed integer")
|
||||
}
|
||||
|
||||
var negate bool
|
||||
if p[0] == '-' {
|
||||
negate = true
|
||||
p = p[1:]
|
||||
if len(p) == 0 {
|
||||
return 0, protocolError("malformed integer")
|
||||
}
|
||||
}
|
||||
|
||||
var n int64
|
||||
for _, b := range p {
|
||||
n *= 10
|
||||
if b < '0' || b > '9' {
|
||||
return 0, protocolError("illegal bytes in length")
|
||||
}
|
||||
n += int64(b - '0')
|
||||
}
|
||||
|
||||
if negate {
|
||||
n = -n
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
var (
|
||||
okReply interface{} = "OK"
|
||||
pongReply interface{} = "PONG"
|
||||
)
|
||||
|
||||
func (c *conn) readReply() (interface{}, error) {
|
||||
line, err := c.readLine()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(line) == 0 {
|
||||
return nil, protocolError("short response line")
|
||||
}
|
||||
switch line[0] {
|
||||
case '+':
|
||||
switch {
|
||||
case len(line) == 3 && line[1] == 'O' && line[2] == 'K':
|
||||
// Avoid allocation for frequent "+OK" response.
|
||||
return okReply, nil
|
||||
case len(line) == 5 && line[1] == 'P' && line[2] == 'O' && line[3] == 'N' && line[4] == 'G':
|
||||
// Avoid allocation in PING command benchmarks :)
|
||||
return pongReply, nil
|
||||
default:
|
||||
return string(line[1:]), nil
|
||||
}
|
||||
case '-':
|
||||
return Error(string(line[1:])), nil
|
||||
case ':':
|
||||
return parseInt(line[1:])
|
||||
case '$':
|
||||
n, err := parseLen(line[1:])
|
||||
if n < 0 || err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := make([]byte, n)
|
||||
_, err = io.ReadFull(c.br, p)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if line, err := c.readLine(); err != nil {
|
||||
return nil, err
|
||||
} else if len(line) != 0 {
|
||||
return nil, protocolError("bad bulk string format")
|
||||
}
|
||||
return p, nil
|
||||
case '*':
|
||||
n, err := parseLen(line[1:])
|
||||
if n < 0 || err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := make([]interface{}, n)
|
||||
for i := range r {
|
||||
r[i], err = c.readReply()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
return nil, protocolError("unexpected response line")
|
||||
}
|
||||
|
||||
func (c *conn) Send(cmd string, args ...interface{}) error {
|
||||
c.mu.Lock()
|
||||
c.pending += 1
|
||||
c.mu.Unlock()
|
||||
if c.writeTimeout != 0 {
|
||||
c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
|
||||
}
|
||||
if err := c.writeCommand(cmd, args); err != nil {
|
||||
return c.fatal(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *conn) Flush() error {
|
||||
if c.writeTimeout != 0 {
|
||||
c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
|
||||
}
|
||||
if err := c.bw.Flush(); err != nil {
|
||||
return c.fatal(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *conn) Receive() (interface{}, error) {
|
||||
return c.ReceiveWithTimeout(c.readTimeout)
|
||||
}
|
||||
|
||||
func (c *conn) ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error) {
|
||||
var deadline time.Time
|
||||
if timeout != 0 {
|
||||
deadline = time.Now().Add(timeout)
|
||||
}
|
||||
c.conn.SetReadDeadline(deadline)
|
||||
|
||||
if reply, err = c.readReply(); err != nil {
|
||||
return nil, c.fatal(err)
|
||||
}
|
||||
// When using pub/sub, the number of receives can be greater than the
|
||||
// number of sends. To enable normal use of the connection after
|
||||
// unsubscribing from all channels, we do not decrement pending to a
|
||||
// negative value.
|
||||
//
|
||||
// The pending field is decremented after the reply is read to handle the
|
||||
// case where Receive is called before Send.
|
||||
c.mu.Lock()
|
||||
if c.pending > 0 {
|
||||
c.pending -= 1
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if err, ok := reply.(Error); ok {
|
||||
return nil, err
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (c *conn) Do(cmd string, args ...interface{}) (interface{}, error) {
|
||||
return c.DoWithTimeout(c.readTimeout, cmd, args...)
|
||||
}
|
||||
|
||||
func (c *conn) DoWithTimeout(readTimeout time.Duration, cmd string, args ...interface{}) (interface{}, error) {
|
||||
c.mu.Lock()
|
||||
pending := c.pending
|
||||
c.pending = 0
|
||||
c.mu.Unlock()
|
||||
|
||||
if cmd == "" && pending == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if c.writeTimeout != 0 {
|
||||
c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
|
||||
}
|
||||
|
||||
if cmd != "" {
|
||||
if err := c.writeCommand(cmd, args); err != nil {
|
||||
return nil, c.fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := c.bw.Flush(); err != nil {
|
||||
return nil, c.fatal(err)
|
||||
}
|
||||
|
||||
var deadline time.Time
|
||||
if readTimeout != 0 {
|
||||
deadline = time.Now().Add(readTimeout)
|
||||
}
|
||||
c.conn.SetReadDeadline(deadline)
|
||||
|
||||
if cmd == "" {
|
||||
reply := make([]interface{}, pending)
|
||||
for i := range reply {
|
||||
r, e := c.readReply()
|
||||
if e != nil {
|
||||
return nil, c.fatal(e)
|
||||
}
|
||||
reply[i] = r
|
||||
}
|
||||
return reply, nil
|
||||
}
|
||||
|
||||
var err error
|
||||
var reply interface{}
|
||||
for i := 0; i <= pending; i++ {
|
||||
var e error
|
||||
if reply, e = c.readReply(); e != nil {
|
||||
return nil, c.fatal(e)
|
||||
}
|
||||
if e, ok := reply.(Error); ok && err == nil {
|
||||
err = e
|
||||
}
|
||||
}
|
||||
return reply, err
|
||||
}
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
// Copyright 2012 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
// Package redis is a client for the Redis database.
|
||||
//
|
||||
// The Redigo FAQ (https://github.com/garyburd/redigo/wiki/FAQ) contains more
|
||||
// documentation about this package.
|
||||
//
|
||||
// Connections
|
||||
//
|
||||
// The Conn interface is the primary interface for working with Redis.
|
||||
// Applications create connections by calling the Dial, DialWithTimeout or
|
||||
// NewConn functions. In the future, functions will be added for creating
|
||||
// sharded and other types of connections.
|
||||
//
|
||||
// The application must call the connection Close method when the application
|
||||
// is done with the connection.
|
||||
//
|
||||
// Executing Commands
|
||||
//
|
||||
// The Conn interface has a generic method for executing Redis commands:
|
||||
//
|
||||
// Do(commandName string, args ...interface{}) (reply interface{}, err error)
|
||||
//
|
||||
// The Redis command reference (http://redis.io/commands) lists the available
|
||||
// commands. An example of using the Redis APPEND command is:
|
||||
//
|
||||
// n, err := conn.Do("APPEND", "key", "value")
|
||||
//
|
||||
// The Do method converts command arguments to bulk strings for transmission
|
||||
// to the server as follows:
|
||||
//
|
||||
// Go Type Conversion
|
||||
// []byte Sent as is
|
||||
// string Sent as is
|
||||
// int, int64 strconv.FormatInt(v)
|
||||
// float64 strconv.FormatFloat(v, 'g', -1, 64)
|
||||
// bool true -> "1", false -> "0"
|
||||
// nil ""
|
||||
// all other types fmt.Fprint(w, v)
|
||||
//
|
||||
// Redis command reply types are represented using the following Go types:
|
||||
//
|
||||
// Redis type Go type
|
||||
// error redis.Error
|
||||
// integer int64
|
||||
// simple string string
|
||||
// bulk string []byte or nil if value not present.
|
||||
// array []interface{} or nil if value not present.
|
||||
//
|
||||
// Use type assertions or the reply helper functions to convert from
|
||||
// interface{} to the specific Go type for the command result.
|
||||
//
|
||||
// Pipelining
|
||||
//
|
||||
// Connections support pipelining using the Send, Flush and Receive methods.
|
||||
//
|
||||
// Send(commandName string, args ...interface{}) error
|
||||
// Flush() error
|
||||
// Receive() (reply interface{}, err error)
|
||||
//
|
||||
// Send writes the command to the connection's output buffer. Flush flushes the
|
||||
// connection's output buffer to the server. Receive reads a single reply from
|
||||
// the server. The following example shows a simple pipeline.
|
||||
//
|
||||
// c.Send("SET", "foo", "bar")
|
||||
// c.Send("GET", "foo")
|
||||
// c.Flush()
|
||||
// c.Receive() // reply from SET
|
||||
// v, err = c.Receive() // reply from GET
|
||||
//
|
||||
// The Do method combines the functionality of the Send, Flush and Receive
|
||||
// methods. The Do method starts by writing the command and flushing the output
|
||||
// buffer. Next, the Do method receives all pending replies including the reply
|
||||
// for the command just sent by Do. If any of the received replies is an error,
|
||||
// then Do returns the error. If there are no errors, then Do returns the last
|
||||
// reply. If the command argument to the Do method is "", then the Do method
|
||||
// will flush the output buffer and receive pending replies without sending a
|
||||
// command.
|
||||
//
|
||||
// Use the Send and Do methods to implement pipelined transactions.
|
||||
//
|
||||
// c.Send("MULTI")
|
||||
// c.Send("INCR", "foo")
|
||||
// c.Send("INCR", "bar")
|
||||
// r, err := c.Do("EXEC")
|
||||
// fmt.Println(r) // prints [1, 1]
|
||||
//
|
||||
// Concurrency
|
||||
//
|
||||
// Connections support one concurrent caller to the Receive method and one
|
||||
// concurrent caller to the Send and Flush methods. No other concurrency is
|
||||
// supported including concurrent calls to the Do method.
|
||||
//
|
||||
// For full concurrent access to Redis, use the thread-safe Pool to get, use
|
||||
// and release a connection from within a goroutine. Connections returned from
|
||||
// a Pool have the concurrency restrictions described in the previous
|
||||
// paragraph.
|
||||
//
|
||||
// Publish and Subscribe
|
||||
//
|
||||
// Use the Send, Flush and Receive methods to implement Pub/Sub subscribers.
|
||||
//
|
||||
// c.Send("SUBSCRIBE", "example")
|
||||
// c.Flush()
|
||||
// for {
|
||||
// reply, err := c.Receive()
|
||||
// if err != nil {
|
||||
// return err
|
||||
// }
|
||||
// // process pushed message
|
||||
// }
|
||||
//
|
||||
// The PubSubConn type wraps a Conn with convenience methods for implementing
|
||||
// subscribers. The Subscribe, PSubscribe, Unsubscribe and PUnsubscribe methods
|
||||
// send and flush a subscription management command. The receive method
|
||||
// converts a pushed message to convenient types for use in a type switch.
|
||||
//
|
||||
// psc := redis.PubSubConn{Conn: c}
|
||||
// psc.Subscribe("example")
|
||||
// for {
|
||||
// switch v := psc.Receive().(type) {
|
||||
// case redis.Message:
|
||||
// fmt.Printf("%s: message: %s\n", v.Channel, v.Data)
|
||||
// case redis.Subscription:
|
||||
// fmt.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
|
||||
// case error:
|
||||
// return v
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// Reply Helpers
|
||||
//
|
||||
// The Bool, Int, Bytes, String, Strings and Values functions convert a reply
|
||||
// to a value of a specific type. To allow convenient wrapping of calls to the
|
||||
// connection Do and Receive methods, the functions take a second argument of
|
||||
// type error. If the error is non-nil, then the helper function returns the
|
||||
// error. If the error is nil, the function converts the reply to the specified
|
||||
// type:
|
||||
//
|
||||
// exists, err := redis.Bool(c.Do("EXISTS", "foo"))
|
||||
// if err != nil {
|
||||
// // handle error return from c.Do or type conversion error.
|
||||
// }
|
||||
//
|
||||
// The Scan function converts elements of a array reply to Go types:
|
||||
//
|
||||
// var value1 int
|
||||
// var value2 string
|
||||
// reply, err := redis.Values(c.Do("MGET", "key1", "key2"))
|
||||
// if err != nil {
|
||||
// // handle error
|
||||
// }
|
||||
// if _, err := redis.Scan(reply, &value1, &value2); err != nil {
|
||||
// // handle error
|
||||
// }
|
||||
//
|
||||
// Errors
|
||||
//
|
||||
// Connection methods return error replies from the server as type redis.Error.
|
||||
//
|
||||
// Call the connection Err() method to determine if the connection encountered
|
||||
// non-recoverable error such as a network error or protocol parsing error. If
|
||||
// Err() returns a non-nil value, then the connection is not usable and should
|
||||
// be closed.
|
||||
package redis // import "github.com/garyburd/redigo/redis"
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
// +build !go1.7
|
||||
|
||||
package redis
|
||||
|
||||
import "crypto/tls"
|
||||
|
||||
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||
return &tls.Config{
|
||||
Rand: cfg.Rand,
|
||||
Time: cfg.Time,
|
||||
Certificates: cfg.Certificates,
|
||||
NameToCertificate: cfg.NameToCertificate,
|
||||
GetCertificate: cfg.GetCertificate,
|
||||
RootCAs: cfg.RootCAs,
|
||||
NextProtos: cfg.NextProtos,
|
||||
ServerName: cfg.ServerName,
|
||||
ClientAuth: cfg.ClientAuth,
|
||||
ClientCAs: cfg.ClientCAs,
|
||||
InsecureSkipVerify: cfg.InsecureSkipVerify,
|
||||
CipherSuites: cfg.CipherSuites,
|
||||
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
|
||||
ClientSessionCache: cfg.ClientSessionCache,
|
||||
MinVersion: cfg.MinVersion,
|
||||
MaxVersion: cfg.MaxVersion,
|
||||
CurvePreferences: cfg.CurvePreferences,
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
// +build go1.7,!go1.8
|
||||
|
||||
package redis
|
||||
|
||||
import "crypto/tls"
|
||||
|
||||
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||
return &tls.Config{
|
||||
Rand: cfg.Rand,
|
||||
Time: cfg.Time,
|
||||
Certificates: cfg.Certificates,
|
||||
NameToCertificate: cfg.NameToCertificate,
|
||||
GetCertificate: cfg.GetCertificate,
|
||||
RootCAs: cfg.RootCAs,
|
||||
NextProtos: cfg.NextProtos,
|
||||
ServerName: cfg.ServerName,
|
||||
ClientAuth: cfg.ClientAuth,
|
||||
ClientCAs: cfg.ClientCAs,
|
||||
InsecureSkipVerify: cfg.InsecureSkipVerify,
|
||||
CipherSuites: cfg.CipherSuites,
|
||||
PreferServerCipherSuites: cfg.PreferServerCipherSuites,
|
||||
ClientSessionCache: cfg.ClientSessionCache,
|
||||
MinVersion: cfg.MinVersion,
|
||||
MaxVersion: cfg.MaxVersion,
|
||||
CurvePreferences: cfg.CurvePreferences,
|
||||
DynamicRecordSizingDisabled: cfg.DynamicRecordSizingDisabled,
|
||||
Renegotiation: cfg.Renegotiation,
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
// +build go1.8
|
||||
|
||||
package redis
|
||||
|
||||
import "crypto/tls"
|
||||
|
||||
func cloneTLSConfig(cfg *tls.Config) *tls.Config {
|
||||
return cfg.Clone()
|
||||
}
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
// Copyright 2012 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package redis
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
_ ConnWithTimeout = (*loggingConn)(nil)
|
||||
)
|
||||
|
||||
// NewLoggingConn returns a logging wrapper around a connection.
|
||||
func NewLoggingConn(conn Conn, logger *log.Logger, prefix string) Conn {
|
||||
if prefix != "" {
|
||||
prefix = prefix + "."
|
||||
}
|
||||
return &loggingConn{conn, logger, prefix}
|
||||
}
|
||||
|
||||
type loggingConn struct {
|
||||
Conn
|
||||
logger *log.Logger
|
||||
prefix string
|
||||
}
|
||||
|
||||
func (c *loggingConn) Close() error {
|
||||
err := c.Conn.Close()
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprintf(&buf, "%sClose() -> (%v)", c.prefix, err)
|
||||
c.logger.Output(2, buf.String())
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *loggingConn) printValue(buf *bytes.Buffer, v interface{}) {
|
||||
const chop = 32
|
||||
switch v := v.(type) {
|
||||
case []byte:
|
||||
if len(v) > chop {
|
||||
fmt.Fprintf(buf, "%q...", v[:chop])
|
||||
} else {
|
||||
fmt.Fprintf(buf, "%q", v)
|
||||
}
|
||||
case string:
|
||||
if len(v) > chop {
|
||||
fmt.Fprintf(buf, "%q...", v[:chop])
|
||||
} else {
|
||||
fmt.Fprintf(buf, "%q", v)
|
||||
}
|
||||
case []interface{}:
|
||||
if len(v) == 0 {
|
||||
buf.WriteString("[]")
|
||||
} else {
|
||||
sep := "["
|
||||
fin := "]"
|
||||
if len(v) > chop {
|
||||
v = v[:chop]
|
||||
fin = "...]"
|
||||
}
|
||||
for _, vv := range v {
|
||||
buf.WriteString(sep)
|
||||
c.printValue(buf, vv)
|
||||
sep = ", "
|
||||
}
|
||||
buf.WriteString(fin)
|
||||
}
|
||||
default:
|
||||
fmt.Fprint(buf, v)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *loggingConn) print(method, commandName string, args []interface{}, reply interface{}, err error) {
|
||||
var buf bytes.Buffer
|
||||
fmt.Fprintf(&buf, "%s%s(", c.prefix, method)
|
||||
if method != "Receive" {
|
||||
buf.WriteString(commandName)
|
||||
for _, arg := range args {
|
||||
buf.WriteString(", ")
|
||||
c.printValue(&buf, arg)
|
||||
}
|
||||
}
|
||||
buf.WriteString(") -> (")
|
||||
if method != "Send" {
|
||||
c.printValue(&buf, reply)
|
||||
buf.WriteString(", ")
|
||||
}
|
||||
fmt.Fprintf(&buf, "%v)", err)
|
||||
c.logger.Output(3, buf.String())
|
||||
}
|
||||
|
||||
func (c *loggingConn) Do(commandName string, args ...interface{}) (interface{}, error) {
|
||||
reply, err := c.Conn.Do(commandName, args...)
|
||||
c.print("Do", commandName, args, reply, err)
|
||||
return reply, err
|
||||
}
|
||||
|
||||
func (c *loggingConn) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (interface{}, error) {
|
||||
reply, err := DoWithTimeout(c.Conn, timeout, commandName, args...)
|
||||
c.print("DoWithTimeout", commandName, args, reply, err)
|
||||
return reply, err
|
||||
}
|
||||
|
||||
func (c *loggingConn) Send(commandName string, args ...interface{}) error {
|
||||
err := c.Conn.Send(commandName, args...)
|
||||
c.print("Send", commandName, args, nil, err)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *loggingConn) Receive() (interface{}, error) {
|
||||
reply, err := c.Conn.Receive()
|
||||
c.print("Receive", "", nil, reply, err)
|
||||
return reply, err
|
||||
}
|
||||
|
||||
func (c *loggingConn) ReceiveWithTimeout(timeout time.Duration) (interface{}, error) {
|
||||
reply, err := ReceiveWithTimeout(c.Conn, timeout)
|
||||
c.print("ReceiveWithTimeout", "", nil, reply, err)
|
||||
return reply, err
|
||||
}
|
||||
+562
@@ -0,0 +1,562 @@
|
||||
// Copyright 2012 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package redis
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"crypto/sha1"
|
||||
"errors"
|
||||
"io"
|
||||
"strconv"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/garyburd/redigo/internal"
|
||||
)
|
||||
|
||||
var (
|
||||
_ ConnWithTimeout = (*activeConn)(nil)
|
||||
_ ConnWithTimeout = (*errorConn)(nil)
|
||||
)
|
||||
|
||||
var nowFunc = time.Now // for testing
|
||||
|
||||
// ErrPoolExhausted is returned from a pool connection method (Do, Send,
|
||||
// Receive, Flush, Err) when the maximum number of database connections in the
|
||||
// pool has been reached.
|
||||
var ErrPoolExhausted = errors.New("redigo: connection pool exhausted")
|
||||
|
||||
var (
|
||||
errPoolClosed = errors.New("redigo: connection pool closed")
|
||||
errConnClosed = errors.New("redigo: connection closed")
|
||||
)
|
||||
|
||||
// Pool maintains a pool of connections. The application calls the Get method
|
||||
// to get a connection from the pool and the connection's Close method to
|
||||
// return the connection's resources to the pool.
|
||||
//
|
||||
// The following example shows how to use a pool in a web application. The
|
||||
// application creates a pool at application startup and makes it available to
|
||||
// request handlers using a package level variable. The pool configuration used
|
||||
// here is an example, not a recommendation.
|
||||
//
|
||||
// func newPool(addr string) *redis.Pool {
|
||||
// return &redis.Pool{
|
||||
// MaxIdle: 3,
|
||||
// IdleTimeout: 240 * time.Second,
|
||||
// Dial: func () (redis.Conn, error) { return redis.Dial("tcp", addr) },
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// var (
|
||||
// pool *redis.Pool
|
||||
// redisServer = flag.String("redisServer", ":6379", "")
|
||||
// )
|
||||
//
|
||||
// func main() {
|
||||
// flag.Parse()
|
||||
// pool = newPool(*redisServer)
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
// A request handler gets a connection from the pool and closes the connection
|
||||
// when the handler is done:
|
||||
//
|
||||
// func serveHome(w http.ResponseWriter, r *http.Request) {
|
||||
// conn := pool.Get()
|
||||
// defer conn.Close()
|
||||
// ...
|
||||
// }
|
||||
//
|
||||
// Use the Dial function to authenticate connections with the AUTH command or
|
||||
// select a database with the SELECT command:
|
||||
//
|
||||
// pool := &redis.Pool{
|
||||
// // Other pool configuration not shown in this example.
|
||||
// Dial: func () (redis.Conn, error) {
|
||||
// c, err := redis.Dial("tcp", server)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// if _, err := c.Do("AUTH", password); err != nil {
|
||||
// c.Close()
|
||||
// return nil, err
|
||||
// }
|
||||
// if _, err := c.Do("SELECT", db); err != nil {
|
||||
// c.Close()
|
||||
// return nil, err
|
||||
// }
|
||||
// return c, nil
|
||||
// },
|
||||
// }
|
||||
//
|
||||
// Use the TestOnBorrow function to check the health of an idle connection
|
||||
// before the connection is returned to the application. This example PINGs
|
||||
// connections that have been idle more than a minute:
|
||||
//
|
||||
// pool := &redis.Pool{
|
||||
// // Other pool configuration not shown in this example.
|
||||
// TestOnBorrow: func(c redis.Conn, t time.Time) error {
|
||||
// if time.Since(t) < time.Minute {
|
||||
// return nil
|
||||
// }
|
||||
// _, err := c.Do("PING")
|
||||
// return err
|
||||
// },
|
||||
// }
|
||||
//
|
||||
type Pool struct {
|
||||
// Dial is an application supplied function for creating and configuring a
|
||||
// connection.
|
||||
//
|
||||
// The connection returned from Dial must not be in a special state
|
||||
// (subscribed to pubsub channel, transaction started, ...).
|
||||
Dial func() (Conn, error)
|
||||
|
||||
// TestOnBorrow is an optional application supplied function for checking
|
||||
// the health of an idle connection before the connection is used again by
|
||||
// the application. Argument t is the time that the connection was returned
|
||||
// to the pool. If the function returns an error, then the connection is
|
||||
// closed.
|
||||
TestOnBorrow func(c Conn, t time.Time) error
|
||||
|
||||
// Maximum number of idle connections in the pool.
|
||||
MaxIdle int
|
||||
|
||||
// Maximum number of connections allocated by the pool at a given time.
|
||||
// When zero, there is no limit on the number of connections in the pool.
|
||||
MaxActive int
|
||||
|
||||
// Close connections after remaining idle for this duration. If the value
|
||||
// is zero, then idle connections are not closed. Applications should set
|
||||
// the timeout to a value less than the server's timeout.
|
||||
IdleTimeout time.Duration
|
||||
|
||||
// If Wait is true and the pool is at the MaxActive limit, then Get() waits
|
||||
// for a connection to be returned to the pool before returning.
|
||||
Wait bool
|
||||
|
||||
// Close connections older than this duration. If the value is zero, then
|
||||
// the pool does not close connections based on age.
|
||||
MaxConnLifetime time.Duration
|
||||
|
||||
chInitialized uint32 // set to 1 when field ch is initialized
|
||||
|
||||
mu sync.Mutex // mu protects the following fields
|
||||
closed bool // set to true when the pool is closed.
|
||||
active int // the number of open connections in the pool
|
||||
ch chan struct{} // limits open connections when p.Wait is true
|
||||
idle idleList // idle connections
|
||||
}
|
||||
|
||||
// NewPool creates a new pool.
|
||||
//
|
||||
// Deprecated: Initialize the Pool directory as shown in the example.
|
||||
func NewPool(newFn func() (Conn, error), maxIdle int) *Pool {
|
||||
return &Pool{Dial: newFn, MaxIdle: maxIdle}
|
||||
}
|
||||
|
||||
// Get gets a connection. The application must close the returned connection.
|
||||
// This method always returns a valid connection so that applications can defer
|
||||
// error handling to the first use of the connection. If there is an error
|
||||
// getting an underlying connection, then the connection Err, Do, Send, Flush
|
||||
// and Receive methods return that error.
|
||||
func (p *Pool) Get() Conn {
|
||||
pc, err := p.get(nil)
|
||||
if err != nil {
|
||||
return errorConn{err}
|
||||
}
|
||||
return &activeConn{p: p, pc: pc}
|
||||
}
|
||||
|
||||
// PoolStats contains pool statistics.
|
||||
type PoolStats struct {
|
||||
// ActiveCount is the number of connections in the pool. The count includes
|
||||
// idle connections and connections in use.
|
||||
ActiveCount int
|
||||
// IdleCount is the number of idle connections in the pool.
|
||||
IdleCount int
|
||||
}
|
||||
|
||||
// Stats returns pool's statistics.
|
||||
func (p *Pool) Stats() PoolStats {
|
||||
p.mu.Lock()
|
||||
stats := PoolStats{
|
||||
ActiveCount: p.active,
|
||||
IdleCount: p.idle.count,
|
||||
}
|
||||
p.mu.Unlock()
|
||||
|
||||
return stats
|
||||
}
|
||||
|
||||
// ActiveCount returns the number of connections in the pool. The count
|
||||
// includes idle connections and connections in use.
|
||||
func (p *Pool) ActiveCount() int {
|
||||
p.mu.Lock()
|
||||
active := p.active
|
||||
p.mu.Unlock()
|
||||
return active
|
||||
}
|
||||
|
||||
// IdleCount returns the number of idle connections in the pool.
|
||||
func (p *Pool) IdleCount() int {
|
||||
p.mu.Lock()
|
||||
idle := p.idle.count
|
||||
p.mu.Unlock()
|
||||
return idle
|
||||
}
|
||||
|
||||
// Close releases the resources used by the pool.
|
||||
func (p *Pool) Close() error {
|
||||
p.mu.Lock()
|
||||
if p.closed {
|
||||
p.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
p.closed = true
|
||||
p.active -= p.idle.count
|
||||
pc := p.idle.front
|
||||
p.idle.count = 0
|
||||
p.idle.front, p.idle.back = nil, nil
|
||||
if p.ch != nil {
|
||||
close(p.ch)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
for ; pc != nil; pc = pc.next {
|
||||
pc.c.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *Pool) lazyInit() {
|
||||
// Fast path.
|
||||
if atomic.LoadUint32(&p.chInitialized) == 1 {
|
||||
return
|
||||
}
|
||||
// Slow path.
|
||||
p.mu.Lock()
|
||||
if p.chInitialized == 0 {
|
||||
p.ch = make(chan struct{}, p.MaxActive)
|
||||
if p.closed {
|
||||
close(p.ch)
|
||||
} else {
|
||||
for i := 0; i < p.MaxActive; i++ {
|
||||
p.ch <- struct{}{}
|
||||
}
|
||||
}
|
||||
atomic.StoreUint32(&p.chInitialized, 1)
|
||||
}
|
||||
p.mu.Unlock()
|
||||
}
|
||||
|
||||
// get prunes stale connections and returns a connection from the idle list or
|
||||
// creates a new connection.
|
||||
func (p *Pool) get(ctx interface {
|
||||
Done() <-chan struct{}
|
||||
Err() error
|
||||
}) (*poolConn, error) {
|
||||
|
||||
// Handle limit for p.Wait == true.
|
||||
if p.Wait && p.MaxActive > 0 {
|
||||
p.lazyInit()
|
||||
if ctx == nil {
|
||||
<-p.ch
|
||||
} else {
|
||||
select {
|
||||
case <-p.ch:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
p.mu.Lock()
|
||||
|
||||
// Prune stale connections at the back of the idle list.
|
||||
if p.IdleTimeout > 0 {
|
||||
n := p.idle.count
|
||||
for i := 0; i < n && p.idle.back != nil && p.idle.back.t.Add(p.IdleTimeout).Before(nowFunc()); i++ {
|
||||
pc := p.idle.back
|
||||
p.idle.popBack()
|
||||
p.mu.Unlock()
|
||||
pc.c.Close()
|
||||
p.mu.Lock()
|
||||
p.active--
|
||||
}
|
||||
}
|
||||
|
||||
// Get idle connection from the front of idle list.
|
||||
for p.idle.front != nil {
|
||||
pc := p.idle.front
|
||||
p.idle.popFront()
|
||||
p.mu.Unlock()
|
||||
if (p.TestOnBorrow == nil || p.TestOnBorrow(pc.c, pc.t) == nil) &&
|
||||
(p.MaxConnLifetime == 0 || nowFunc().Sub(pc.created) < p.MaxConnLifetime) {
|
||||
return pc, nil
|
||||
}
|
||||
pc.c.Close()
|
||||
p.mu.Lock()
|
||||
p.active--
|
||||
}
|
||||
|
||||
// Check for pool closed before dialing a new connection.
|
||||
if p.closed {
|
||||
p.mu.Unlock()
|
||||
return nil, errors.New("redigo: get on closed pool")
|
||||
}
|
||||
|
||||
// Handle limit for p.Wait == false.
|
||||
if !p.Wait && p.MaxActive > 0 && p.active >= p.MaxActive {
|
||||
p.mu.Unlock()
|
||||
return nil, ErrPoolExhausted
|
||||
}
|
||||
|
||||
p.active++
|
||||
p.mu.Unlock()
|
||||
c, err := p.Dial()
|
||||
if err != nil {
|
||||
c = nil
|
||||
p.mu.Lock()
|
||||
p.active--
|
||||
if p.ch != nil && !p.closed {
|
||||
p.ch <- struct{}{}
|
||||
}
|
||||
p.mu.Unlock()
|
||||
}
|
||||
return &poolConn{c: c, created: nowFunc()}, err
|
||||
}
|
||||
|
||||
func (p *Pool) put(pc *poolConn, forceClose bool) error {
|
||||
p.mu.Lock()
|
||||
if !p.closed && !forceClose {
|
||||
pc.t = nowFunc()
|
||||
p.idle.pushFront(pc)
|
||||
if p.idle.count > p.MaxIdle {
|
||||
pc = p.idle.back
|
||||
p.idle.popBack()
|
||||
} else {
|
||||
pc = nil
|
||||
}
|
||||
}
|
||||
|
||||
if pc != nil {
|
||||
p.mu.Unlock()
|
||||
pc.c.Close()
|
||||
p.mu.Lock()
|
||||
p.active--
|
||||
}
|
||||
|
||||
if p.ch != nil && !p.closed {
|
||||
p.ch <- struct{}{}
|
||||
}
|
||||
p.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
type activeConn struct {
|
||||
p *Pool
|
||||
pc *poolConn
|
||||
state int
|
||||
}
|
||||
|
||||
var (
|
||||
sentinel []byte
|
||||
sentinelOnce sync.Once
|
||||
)
|
||||
|
||||
func initSentinel() {
|
||||
p := make([]byte, 64)
|
||||
if _, err := rand.Read(p); err == nil {
|
||||
sentinel = p
|
||||
} else {
|
||||
h := sha1.New()
|
||||
io.WriteString(h, "Oops, rand failed. Use time instead.")
|
||||
io.WriteString(h, strconv.FormatInt(time.Now().UnixNano(), 10))
|
||||
sentinel = h.Sum(nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (ac *activeConn) Close() error {
|
||||
pc := ac.pc
|
||||
if pc == nil {
|
||||
return nil
|
||||
}
|
||||
ac.pc = nil
|
||||
|
||||
if ac.state&internal.MultiState != 0 {
|
||||
pc.c.Send("DISCARD")
|
||||
ac.state &^= (internal.MultiState | internal.WatchState)
|
||||
} else if ac.state&internal.WatchState != 0 {
|
||||
pc.c.Send("UNWATCH")
|
||||
ac.state &^= internal.WatchState
|
||||
}
|
||||
if ac.state&internal.SubscribeState != 0 {
|
||||
pc.c.Send("UNSUBSCRIBE")
|
||||
pc.c.Send("PUNSUBSCRIBE")
|
||||
// To detect the end of the message stream, ask the server to echo
|
||||
// a sentinel value and read until we see that value.
|
||||
sentinelOnce.Do(initSentinel)
|
||||
pc.c.Send("ECHO", sentinel)
|
||||
pc.c.Flush()
|
||||
for {
|
||||
p, err := pc.c.Receive()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if p, ok := p.([]byte); ok && bytes.Equal(p, sentinel) {
|
||||
ac.state &^= internal.SubscribeState
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
pc.c.Do("")
|
||||
ac.p.put(pc, ac.state != 0 || pc.c.Err() != nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ac *activeConn) Err() error {
|
||||
pc := ac.pc
|
||||
if pc == nil {
|
||||
return errConnClosed
|
||||
}
|
||||
return pc.c.Err()
|
||||
}
|
||||
|
||||
func (ac *activeConn) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
|
||||
pc := ac.pc
|
||||
if pc == nil {
|
||||
return nil, errConnClosed
|
||||
}
|
||||
ci := internal.LookupCommandInfo(commandName)
|
||||
ac.state = (ac.state | ci.Set) &^ ci.Clear
|
||||
return pc.c.Do(commandName, args...)
|
||||
}
|
||||
|
||||
func (ac *activeConn) DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (reply interface{}, err error) {
|
||||
pc := ac.pc
|
||||
if pc == nil {
|
||||
return nil, errConnClosed
|
||||
}
|
||||
cwt, ok := pc.c.(ConnWithTimeout)
|
||||
if !ok {
|
||||
return nil, errTimeoutNotSupported
|
||||
}
|
||||
ci := internal.LookupCommandInfo(commandName)
|
||||
ac.state = (ac.state | ci.Set) &^ ci.Clear
|
||||
return cwt.DoWithTimeout(timeout, commandName, args...)
|
||||
}
|
||||
|
||||
func (ac *activeConn) Send(commandName string, args ...interface{}) error {
|
||||
pc := ac.pc
|
||||
if pc == nil {
|
||||
return errConnClosed
|
||||
}
|
||||
ci := internal.LookupCommandInfo(commandName)
|
||||
ac.state = (ac.state | ci.Set) &^ ci.Clear
|
||||
return pc.c.Send(commandName, args...)
|
||||
}
|
||||
|
||||
func (ac *activeConn) Flush() error {
|
||||
pc := ac.pc
|
||||
if pc == nil {
|
||||
return errConnClosed
|
||||
}
|
||||
return pc.c.Flush()
|
||||
}
|
||||
|
||||
func (ac *activeConn) Receive() (reply interface{}, err error) {
|
||||
pc := ac.pc
|
||||
if pc == nil {
|
||||
return nil, errConnClosed
|
||||
}
|
||||
return pc.c.Receive()
|
||||
}
|
||||
|
||||
func (ac *activeConn) ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error) {
|
||||
pc := ac.pc
|
||||
if pc == nil {
|
||||
return nil, errConnClosed
|
||||
}
|
||||
cwt, ok := pc.c.(ConnWithTimeout)
|
||||
if !ok {
|
||||
return nil, errTimeoutNotSupported
|
||||
}
|
||||
return cwt.ReceiveWithTimeout(timeout)
|
||||
}
|
||||
|
||||
type errorConn struct{ err error }
|
||||
|
||||
func (ec errorConn) Do(string, ...interface{}) (interface{}, error) { return nil, ec.err }
|
||||
func (ec errorConn) DoWithTimeout(time.Duration, string, ...interface{}) (interface{}, error) {
|
||||
return nil, ec.err
|
||||
}
|
||||
func (ec errorConn) Send(string, ...interface{}) error { return ec.err }
|
||||
func (ec errorConn) Err() error { return ec.err }
|
||||
func (ec errorConn) Close() error { return nil }
|
||||
func (ec errorConn) Flush() error { return ec.err }
|
||||
func (ec errorConn) Receive() (interface{}, error) { return nil, ec.err }
|
||||
func (ec errorConn) ReceiveWithTimeout(time.Duration) (interface{}, error) { return nil, ec.err }
|
||||
|
||||
type idleList struct {
|
||||
count int
|
||||
front, back *poolConn
|
||||
}
|
||||
|
||||
type poolConn struct {
|
||||
c Conn
|
||||
t time.Time
|
||||
created time.Time
|
||||
next, prev *poolConn
|
||||
}
|
||||
|
||||
func (l *idleList) pushFront(pc *poolConn) {
|
||||
pc.next = l.front
|
||||
pc.prev = nil
|
||||
if l.count == 0 {
|
||||
l.back = pc
|
||||
} else {
|
||||
l.front.prev = pc
|
||||
}
|
||||
l.front = pc
|
||||
l.count++
|
||||
return
|
||||
}
|
||||
|
||||
func (l *idleList) popFront() {
|
||||
pc := l.front
|
||||
l.count--
|
||||
if l.count == 0 {
|
||||
l.front, l.back = nil, nil
|
||||
} else {
|
||||
pc.next.prev = nil
|
||||
l.front = pc.next
|
||||
}
|
||||
pc.next, pc.prev = nil, nil
|
||||
}
|
||||
|
||||
func (l *idleList) popBack() {
|
||||
pc := l.back
|
||||
l.count--
|
||||
if l.count == 0 {
|
||||
l.front, l.back = nil, nil
|
||||
} else {
|
||||
pc.prev.next = nil
|
||||
l.back = pc.prev
|
||||
}
|
||||
pc.next, pc.prev = nil, nil
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
// Copyright 2018 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
// +build go1.7
|
||||
|
||||
package redis
|
||||
|
||||
import "context"
|
||||
|
||||
// GetContext gets a connection using the provided context.
|
||||
//
|
||||
// The provided Context must be non-nil. If the context expires before the
|
||||
// connection is complete, an error is returned. Any expiration on the context
|
||||
// will not affect the returned connection.
|
||||
//
|
||||
// If the function completes without error, then the application must close the
|
||||
// returned connection.
|
||||
func (p *Pool) GetContext(ctx context.Context) (Conn, error) {
|
||||
pc, err := p.get(ctx)
|
||||
if err != nil {
|
||||
return errorConn{err}, err
|
||||
}
|
||||
return &activeConn{p: p, pc: pc}, nil
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
// Copyright 2012 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package redis
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Subscription represents a subscribe or unsubscribe notification.
|
||||
type Subscription struct {
|
||||
// Kind is "subscribe", "unsubscribe", "psubscribe" or "punsubscribe"
|
||||
Kind string
|
||||
|
||||
// The channel that was changed.
|
||||
Channel string
|
||||
|
||||
// The current number of subscriptions for connection.
|
||||
Count int
|
||||
}
|
||||
|
||||
// Message represents a message notification.
|
||||
type Message struct {
|
||||
// The originating channel.
|
||||
Channel string
|
||||
|
||||
// The message data.
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// PMessage represents a pmessage notification.
|
||||
type PMessage struct {
|
||||
// The matched pattern.
|
||||
Pattern string
|
||||
|
||||
// The originating channel.
|
||||
Channel string
|
||||
|
||||
// The message data.
|
||||
Data []byte
|
||||
}
|
||||
|
||||
// Pong represents a pubsub pong notification.
|
||||
type Pong struct {
|
||||
Data string
|
||||
}
|
||||
|
||||
// PubSubConn wraps a Conn with convenience methods for subscribers.
|
||||
type PubSubConn struct {
|
||||
Conn Conn
|
||||
}
|
||||
|
||||
// Close closes the connection.
|
||||
func (c PubSubConn) Close() error {
|
||||
return c.Conn.Close()
|
||||
}
|
||||
|
||||
// Subscribe subscribes the connection to the specified channels.
|
||||
func (c PubSubConn) Subscribe(channel ...interface{}) error {
|
||||
c.Conn.Send("SUBSCRIBE", channel...)
|
||||
return c.Conn.Flush()
|
||||
}
|
||||
|
||||
// PSubscribe subscribes the connection to the given patterns.
|
||||
func (c PubSubConn) PSubscribe(channel ...interface{}) error {
|
||||
c.Conn.Send("PSUBSCRIBE", channel...)
|
||||
return c.Conn.Flush()
|
||||
}
|
||||
|
||||
// Unsubscribe unsubscribes the connection from the given channels, or from all
|
||||
// of them if none is given.
|
||||
func (c PubSubConn) Unsubscribe(channel ...interface{}) error {
|
||||
c.Conn.Send("UNSUBSCRIBE", channel...)
|
||||
return c.Conn.Flush()
|
||||
}
|
||||
|
||||
// PUnsubscribe unsubscribes the connection from the given patterns, or from all
|
||||
// of them if none is given.
|
||||
func (c PubSubConn) PUnsubscribe(channel ...interface{}) error {
|
||||
c.Conn.Send("PUNSUBSCRIBE", channel...)
|
||||
return c.Conn.Flush()
|
||||
}
|
||||
|
||||
// Ping sends a PING to the server with the specified data.
|
||||
//
|
||||
// The connection must be subscribed to at least one channel or pattern when
|
||||
// calling this method.
|
||||
func (c PubSubConn) Ping(data string) error {
|
||||
c.Conn.Send("PING", data)
|
||||
return c.Conn.Flush()
|
||||
}
|
||||
|
||||
// Receive returns a pushed message as a Subscription, Message, PMessage, Pong
|
||||
// or error. The return value is intended to be used directly in a type switch
|
||||
// as illustrated in the PubSubConn example.
|
||||
func (c PubSubConn) Receive() interface{} {
|
||||
return c.receiveInternal(c.Conn.Receive())
|
||||
}
|
||||
|
||||
// ReceiveWithTimeout is like Receive, but it allows the application to
|
||||
// override the connection's default timeout.
|
||||
func (c PubSubConn) ReceiveWithTimeout(timeout time.Duration) interface{} {
|
||||
return c.receiveInternal(ReceiveWithTimeout(c.Conn, timeout))
|
||||
}
|
||||
|
||||
func (c PubSubConn) receiveInternal(replyArg interface{}, errArg error) interface{} {
|
||||
reply, err := Values(replyArg, errArg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var kind string
|
||||
reply, err = Scan(reply, &kind)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch kind {
|
||||
case "message":
|
||||
var m Message
|
||||
if _, err := Scan(reply, &m.Channel, &m.Data); err != nil {
|
||||
return err
|
||||
}
|
||||
return m
|
||||
case "pmessage":
|
||||
var pm PMessage
|
||||
if _, err := Scan(reply, &pm.Pattern, &pm.Channel, &pm.Data); err != nil {
|
||||
return err
|
||||
}
|
||||
return pm
|
||||
case "subscribe", "psubscribe", "unsubscribe", "punsubscribe":
|
||||
s := Subscription{Kind: kind}
|
||||
if _, err := Scan(reply, &s.Channel, &s.Count); err != nil {
|
||||
return err
|
||||
}
|
||||
return s
|
||||
case "pong":
|
||||
var p Pong
|
||||
if _, err := Scan(reply, &p.Data); err != nil {
|
||||
return err
|
||||
}
|
||||
return p
|
||||
}
|
||||
return errors.New("redigo: unknown pubsub notification")
|
||||
}
|
||||
+117
@@ -0,0 +1,117 @@
|
||||
// Copyright 2012 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package redis
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Error represents an error returned in a command reply.
|
||||
type Error string
|
||||
|
||||
func (err Error) Error() string { return string(err) }
|
||||
|
||||
// Conn represents a connection to a Redis server.
|
||||
type Conn interface {
|
||||
// Close closes the connection.
|
||||
Close() error
|
||||
|
||||
// Err returns a non-nil value when the connection is not usable.
|
||||
Err() error
|
||||
|
||||
// Do sends a command to the server and returns the received reply.
|
||||
Do(commandName string, args ...interface{}) (reply interface{}, err error)
|
||||
|
||||
// Send writes the command to the client's output buffer.
|
||||
Send(commandName string, args ...interface{}) error
|
||||
|
||||
// Flush flushes the output buffer to the Redis server.
|
||||
Flush() error
|
||||
|
||||
// Receive receives a single reply from the Redis server
|
||||
Receive() (reply interface{}, err error)
|
||||
}
|
||||
|
||||
// Argument is the interface implemented by an object which wants to control how
|
||||
// the object is converted to Redis bulk strings.
|
||||
type Argument interface {
|
||||
// RedisArg returns a value to be encoded as a bulk string per the
|
||||
// conversions listed in the section 'Executing Commands'.
|
||||
// Implementations should typically return a []byte or string.
|
||||
RedisArg() interface{}
|
||||
}
|
||||
|
||||
// Scanner is implemented by an object which wants to control its value is
|
||||
// interpreted when read from Redis.
|
||||
type Scanner interface {
|
||||
// RedisScan assigns a value from a Redis value. The argument src is one of
|
||||
// the reply types listed in the section `Executing Commands`.
|
||||
//
|
||||
// An error should be returned if the value cannot be stored without
|
||||
// loss of information.
|
||||
RedisScan(src interface{}) error
|
||||
}
|
||||
|
||||
// ConnWithTimeout is an optional interface that allows the caller to override
|
||||
// a connection's default read timeout. This interface is useful for executing
|
||||
// the BLPOP, BRPOP, BRPOPLPUSH, XREAD and other commands that block at the
|
||||
// server.
|
||||
//
|
||||
// A connection's default read timeout is set with the DialReadTimeout dial
|
||||
// option. Applications should rely on the default timeout for commands that do
|
||||
// not block at the server.
|
||||
//
|
||||
// All of the Conn implementations in this package satisfy the ConnWithTimeout
|
||||
// interface.
|
||||
//
|
||||
// Use the DoWithTimeout and ReceiveWithTimeout helper functions to simplify
|
||||
// use of this interface.
|
||||
type ConnWithTimeout interface {
|
||||
Conn
|
||||
|
||||
// Do sends a command to the server and returns the received reply.
|
||||
// The timeout overrides the read timeout set when dialing the
|
||||
// connection.
|
||||
DoWithTimeout(timeout time.Duration, commandName string, args ...interface{}) (reply interface{}, err error)
|
||||
|
||||
// Receive receives a single reply from the Redis server. The timeout
|
||||
// overrides the read timeout set when dialing the connection.
|
||||
ReceiveWithTimeout(timeout time.Duration) (reply interface{}, err error)
|
||||
}
|
||||
|
||||
var errTimeoutNotSupported = errors.New("redis: connection does not support ConnWithTimeout")
|
||||
|
||||
// DoWithTimeout executes a Redis command with the specified read timeout. If
|
||||
// the connection does not satisfy the ConnWithTimeout interface, then an error
|
||||
// is returned.
|
||||
func DoWithTimeout(c Conn, timeout time.Duration, cmd string, args ...interface{}) (interface{}, error) {
|
||||
cwt, ok := c.(ConnWithTimeout)
|
||||
if !ok {
|
||||
return nil, errTimeoutNotSupported
|
||||
}
|
||||
return cwt.DoWithTimeout(timeout, cmd, args...)
|
||||
}
|
||||
|
||||
// ReceiveWithTimeout receives a reply with the specified read timeout. If the
|
||||
// connection does not satisfy the ConnWithTimeout interface, then an error is
|
||||
// returned.
|
||||
func ReceiveWithTimeout(c Conn, timeout time.Duration) (interface{}, error) {
|
||||
cwt, ok := c.(ConnWithTimeout)
|
||||
if !ok {
|
||||
return nil, errTimeoutNotSupported
|
||||
}
|
||||
return cwt.ReceiveWithTimeout(timeout)
|
||||
}
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
// Copyright 2012 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package redis
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// ErrNil indicates that a reply value is nil.
|
||||
var ErrNil = errors.New("redigo: nil returned")
|
||||
|
||||
// Int is a helper that converts a command reply to an integer. If err is not
|
||||
// equal to nil, then Int returns 0, err. Otherwise, Int converts the
|
||||
// reply to an int as follows:
|
||||
//
|
||||
// Reply type Result
|
||||
// integer int(reply), nil
|
||||
// bulk string parsed reply, nil
|
||||
// nil 0, ErrNil
|
||||
// other 0, error
|
||||
func Int(reply interface{}, err error) (int, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case int64:
|
||||
x := int(reply)
|
||||
if int64(x) != reply {
|
||||
return 0, strconv.ErrRange
|
||||
}
|
||||
return x, nil
|
||||
case []byte:
|
||||
n, err := strconv.ParseInt(string(reply), 10, 0)
|
||||
return int(n), err
|
||||
case nil:
|
||||
return 0, ErrNil
|
||||
case Error:
|
||||
return 0, reply
|
||||
}
|
||||
return 0, fmt.Errorf("redigo: unexpected type for Int, got type %T", reply)
|
||||
}
|
||||
|
||||
// Int64 is a helper that converts a command reply to 64 bit integer. If err is
|
||||
// not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the
|
||||
// reply to an int64 as follows:
|
||||
//
|
||||
// Reply type Result
|
||||
// integer reply, nil
|
||||
// bulk string parsed reply, nil
|
||||
// nil 0, ErrNil
|
||||
// other 0, error
|
||||
func Int64(reply interface{}, err error) (int64, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case int64:
|
||||
return reply, nil
|
||||
case []byte:
|
||||
n, err := strconv.ParseInt(string(reply), 10, 64)
|
||||
return n, err
|
||||
case nil:
|
||||
return 0, ErrNil
|
||||
case Error:
|
||||
return 0, reply
|
||||
}
|
||||
return 0, fmt.Errorf("redigo: unexpected type for Int64, got type %T", reply)
|
||||
}
|
||||
|
||||
var errNegativeInt = errors.New("redigo: unexpected value for Uint64")
|
||||
|
||||
// Uint64 is a helper that converts a command reply to 64 bit integer. If err is
|
||||
// not equal to nil, then Int returns 0, err. Otherwise, Int64 converts the
|
||||
// reply to an int64 as follows:
|
||||
//
|
||||
// Reply type Result
|
||||
// integer reply, nil
|
||||
// bulk string parsed reply, nil
|
||||
// nil 0, ErrNil
|
||||
// other 0, error
|
||||
func Uint64(reply interface{}, err error) (uint64, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case int64:
|
||||
if reply < 0 {
|
||||
return 0, errNegativeInt
|
||||
}
|
||||
return uint64(reply), nil
|
||||
case []byte:
|
||||
n, err := strconv.ParseUint(string(reply), 10, 64)
|
||||
return n, err
|
||||
case nil:
|
||||
return 0, ErrNil
|
||||
case Error:
|
||||
return 0, reply
|
||||
}
|
||||
return 0, fmt.Errorf("redigo: unexpected type for Uint64, got type %T", reply)
|
||||
}
|
||||
|
||||
// Float64 is a helper that converts a command reply to 64 bit float. If err is
|
||||
// not equal to nil, then Float64 returns 0, err. Otherwise, Float64 converts
|
||||
// the reply to an int as follows:
|
||||
//
|
||||
// Reply type Result
|
||||
// bulk string parsed reply, nil
|
||||
// nil 0, ErrNil
|
||||
// other 0, error
|
||||
func Float64(reply interface{}, err error) (float64, error) {
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case []byte:
|
||||
n, err := strconv.ParseFloat(string(reply), 64)
|
||||
return n, err
|
||||
case nil:
|
||||
return 0, ErrNil
|
||||
case Error:
|
||||
return 0, reply
|
||||
}
|
||||
return 0, fmt.Errorf("redigo: unexpected type for Float64, got type %T", reply)
|
||||
}
|
||||
|
||||
// String is a helper that converts a command reply to a string. If err is not
|
||||
// equal to nil, then String returns "", err. Otherwise String converts the
|
||||
// reply to a string as follows:
|
||||
//
|
||||
// Reply type Result
|
||||
// bulk string string(reply), nil
|
||||
// simple string reply, nil
|
||||
// nil "", ErrNil
|
||||
// other "", error
|
||||
func String(reply interface{}, err error) (string, error) {
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case []byte:
|
||||
return string(reply), nil
|
||||
case string:
|
||||
return reply, nil
|
||||
case nil:
|
||||
return "", ErrNil
|
||||
case Error:
|
||||
return "", reply
|
||||
}
|
||||
return "", fmt.Errorf("redigo: unexpected type for String, got type %T", reply)
|
||||
}
|
||||
|
||||
// Bytes is a helper that converts a command reply to a slice of bytes. If err
|
||||
// is not equal to nil, then Bytes returns nil, err. Otherwise Bytes converts
|
||||
// the reply to a slice of bytes as follows:
|
||||
//
|
||||
// Reply type Result
|
||||
// bulk string reply, nil
|
||||
// simple string []byte(reply), nil
|
||||
// nil nil, ErrNil
|
||||
// other nil, error
|
||||
func Bytes(reply interface{}, err error) ([]byte, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case []byte:
|
||||
return reply, nil
|
||||
case string:
|
||||
return []byte(reply), nil
|
||||
case nil:
|
||||
return nil, ErrNil
|
||||
case Error:
|
||||
return nil, reply
|
||||
}
|
||||
return nil, fmt.Errorf("redigo: unexpected type for Bytes, got type %T", reply)
|
||||
}
|
||||
|
||||
// Bool is a helper that converts a command reply to a boolean. If err is not
|
||||
// equal to nil, then Bool returns false, err. Otherwise Bool converts the
|
||||
// reply to boolean as follows:
|
||||
//
|
||||
// Reply type Result
|
||||
// integer value != 0, nil
|
||||
// bulk string strconv.ParseBool(reply)
|
||||
// nil false, ErrNil
|
||||
// other false, error
|
||||
func Bool(reply interface{}, err error) (bool, error) {
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case int64:
|
||||
return reply != 0, nil
|
||||
case []byte:
|
||||
return strconv.ParseBool(string(reply))
|
||||
case nil:
|
||||
return false, ErrNil
|
||||
case Error:
|
||||
return false, reply
|
||||
}
|
||||
return false, fmt.Errorf("redigo: unexpected type for Bool, got type %T", reply)
|
||||
}
|
||||
|
||||
// MultiBulk is a helper that converts an array command reply to a []interface{}.
|
||||
//
|
||||
// Deprecated: Use Values instead.
|
||||
func MultiBulk(reply interface{}, err error) ([]interface{}, error) { return Values(reply, err) }
|
||||
|
||||
// Values is a helper that converts an array command reply to a []interface{}.
|
||||
// If err is not equal to nil, then Values returns nil, err. Otherwise, Values
|
||||
// converts the reply as follows:
|
||||
//
|
||||
// Reply type Result
|
||||
// array reply, nil
|
||||
// nil nil, ErrNil
|
||||
// other nil, error
|
||||
func Values(reply interface{}, err error) ([]interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case []interface{}:
|
||||
return reply, nil
|
||||
case nil:
|
||||
return nil, ErrNil
|
||||
case Error:
|
||||
return nil, reply
|
||||
}
|
||||
return nil, fmt.Errorf("redigo: unexpected type for Values, got type %T", reply)
|
||||
}
|
||||
|
||||
func sliceHelper(reply interface{}, err error, name string, makeSlice func(int), assign func(int, interface{}) error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch reply := reply.(type) {
|
||||
case []interface{}:
|
||||
makeSlice(len(reply))
|
||||
for i := range reply {
|
||||
if reply[i] == nil {
|
||||
continue
|
||||
}
|
||||
if err := assign(i, reply[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
case nil:
|
||||
return ErrNil
|
||||
case Error:
|
||||
return reply
|
||||
}
|
||||
return fmt.Errorf("redigo: unexpected type for %s, got type %T", name, reply)
|
||||
}
|
||||
|
||||
// Float64s is a helper that converts an array command reply to a []float64. If
|
||||
// err is not equal to nil, then Float64s returns nil, err. Nil array items are
|
||||
// converted to 0 in the output slice. Floats64 returns an error if an array
|
||||
// item is not a bulk string or nil.
|
||||
func Float64s(reply interface{}, err error) ([]float64, error) {
|
||||
var result []float64
|
||||
err = sliceHelper(reply, err, "Float64s", func(n int) { result = make([]float64, n) }, func(i int, v interface{}) error {
|
||||
p, ok := v.([]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("redigo: unexpected element type for Floats64, got type %T", v)
|
||||
}
|
||||
f, err := strconv.ParseFloat(string(p), 64)
|
||||
result[i] = f
|
||||
return err
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
// Strings is a helper that converts an array command reply to a []string. If
|
||||
// err is not equal to nil, then Strings returns nil, err. Nil array items are
|
||||
// converted to "" in the output slice. Strings returns an error if an array
|
||||
// item is not a bulk string or nil.
|
||||
func Strings(reply interface{}, err error) ([]string, error) {
|
||||
var result []string
|
||||
err = sliceHelper(reply, err, "Strings", func(n int) { result = make([]string, n) }, func(i int, v interface{}) error {
|
||||
switch v := v.(type) {
|
||||
case string:
|
||||
result[i] = v
|
||||
return nil
|
||||
case []byte:
|
||||
result[i] = string(v)
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("redigo: unexpected element type for Strings, got type %T", v)
|
||||
}
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
// ByteSlices is a helper that converts an array command reply to a [][]byte.
|
||||
// If err is not equal to nil, then ByteSlices returns nil, err. Nil array
|
||||
// items are stay nil. ByteSlices returns an error if an array item is not a
|
||||
// bulk string or nil.
|
||||
func ByteSlices(reply interface{}, err error) ([][]byte, error) {
|
||||
var result [][]byte
|
||||
err = sliceHelper(reply, err, "ByteSlices", func(n int) { result = make([][]byte, n) }, func(i int, v interface{}) error {
|
||||
p, ok := v.([]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("redigo: unexpected element type for ByteSlices, got type %T", v)
|
||||
}
|
||||
result[i] = p
|
||||
return nil
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
// Int64s is a helper that converts an array command reply to a []int64.
|
||||
// If err is not equal to nil, then Int64s returns nil, err. Nil array
|
||||
// items are stay nil. Int64s returns an error if an array item is not a
|
||||
// bulk string or nil.
|
||||
func Int64s(reply interface{}, err error) ([]int64, error) {
|
||||
var result []int64
|
||||
err = sliceHelper(reply, err, "Int64s", func(n int) { result = make([]int64, n) }, func(i int, v interface{}) error {
|
||||
switch v := v.(type) {
|
||||
case int64:
|
||||
result[i] = v
|
||||
return nil
|
||||
case []byte:
|
||||
n, err := strconv.ParseInt(string(v), 10, 64)
|
||||
result[i] = n
|
||||
return err
|
||||
default:
|
||||
return fmt.Errorf("redigo: unexpected element type for Int64s, got type %T", v)
|
||||
}
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
// Ints is a helper that converts an array command reply to a []in.
|
||||
// If err is not equal to nil, then Ints returns nil, err. Nil array
|
||||
// items are stay nil. Ints returns an error if an array item is not a
|
||||
// bulk string or nil.
|
||||
func Ints(reply interface{}, err error) ([]int, error) {
|
||||
var result []int
|
||||
err = sliceHelper(reply, err, "Ints", func(n int) { result = make([]int, n) }, func(i int, v interface{}) error {
|
||||
switch v := v.(type) {
|
||||
case int64:
|
||||
n := int(v)
|
||||
if int64(n) != v {
|
||||
return strconv.ErrRange
|
||||
}
|
||||
result[i] = n
|
||||
return nil
|
||||
case []byte:
|
||||
n, err := strconv.Atoi(string(v))
|
||||
result[i] = n
|
||||
return err
|
||||
default:
|
||||
return fmt.Errorf("redigo: unexpected element type for Ints, got type %T", v)
|
||||
}
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
|
||||
// StringMap is a helper that converts an array of strings (alternating key, value)
|
||||
// into a map[string]string. The HGETALL and CONFIG GET commands return replies in this format.
|
||||
// Requires an even number of values in result.
|
||||
func StringMap(result interface{}, err error) (map[string]string, error) {
|
||||
values, err := Values(result, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(values)%2 != 0 {
|
||||
return nil, errors.New("redigo: StringMap expects even number of values result")
|
||||
}
|
||||
m := make(map[string]string, len(values)/2)
|
||||
for i := 0; i < len(values); i += 2 {
|
||||
key, okKey := values[i].([]byte)
|
||||
value, okValue := values[i+1].([]byte)
|
||||
if !okKey || !okValue {
|
||||
return nil, errors.New("redigo: StringMap key not a bulk string value")
|
||||
}
|
||||
m[string(key)] = string(value)
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// IntMap is a helper that converts an array of strings (alternating key, value)
|
||||
// into a map[string]int. The HGETALL commands return replies in this format.
|
||||
// Requires an even number of values in result.
|
||||
func IntMap(result interface{}, err error) (map[string]int, error) {
|
||||
values, err := Values(result, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(values)%2 != 0 {
|
||||
return nil, errors.New("redigo: IntMap expects even number of values result")
|
||||
}
|
||||
m := make(map[string]int, len(values)/2)
|
||||
for i := 0; i < len(values); i += 2 {
|
||||
key, ok := values[i].([]byte)
|
||||
if !ok {
|
||||
return nil, errors.New("redigo: IntMap key not a bulk string value")
|
||||
}
|
||||
value, err := Int(values[i+1], nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m[string(key)] = value
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Int64Map is a helper that converts an array of strings (alternating key, value)
|
||||
// into a map[string]int64. The HGETALL commands return replies in this format.
|
||||
// Requires an even number of values in result.
|
||||
func Int64Map(result interface{}, err error) (map[string]int64, error) {
|
||||
values, err := Values(result, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(values)%2 != 0 {
|
||||
return nil, errors.New("redigo: Int64Map expects even number of values result")
|
||||
}
|
||||
m := make(map[string]int64, len(values)/2)
|
||||
for i := 0; i < len(values); i += 2 {
|
||||
key, ok := values[i].([]byte)
|
||||
if !ok {
|
||||
return nil, errors.New("redigo: Int64Map key not a bulk string value")
|
||||
}
|
||||
value, err := Int64(values[i+1], nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m[string(key)] = value
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Positions is a helper that converts an array of positions (lat, long)
|
||||
// into a [][2]float64. The GEOPOS command returns replies in this format.
|
||||
func Positions(result interface{}, err error) ([]*[2]float64, error) {
|
||||
values, err := Values(result, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
positions := make([]*[2]float64, len(values))
|
||||
for i := range values {
|
||||
if values[i] == nil {
|
||||
continue
|
||||
}
|
||||
p, ok := values[i].([]interface{})
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("redigo: unexpected element type for interface slice, got type %T", values[i])
|
||||
}
|
||||
if len(p) != 2 {
|
||||
return nil, fmt.Errorf("redigo: unexpected number of values for a member position, got %d", len(p))
|
||||
}
|
||||
lat, err := Float64(p[0], nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
long, err := Float64(p[1], nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
positions[i] = &[2]float64{lat, long}
|
||||
}
|
||||
return positions, nil
|
||||
}
|
||||
+585
@@ -0,0 +1,585 @@
|
||||
// Copyright 2012 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package redis
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
func ensureLen(d reflect.Value, n int) {
|
||||
if n > d.Cap() {
|
||||
d.Set(reflect.MakeSlice(d.Type(), n, n))
|
||||
} else {
|
||||
d.SetLen(n)
|
||||
}
|
||||
}
|
||||
|
||||
func cannotConvert(d reflect.Value, s interface{}) error {
|
||||
var sname string
|
||||
switch s.(type) {
|
||||
case string:
|
||||
sname = "Redis simple string"
|
||||
case Error:
|
||||
sname = "Redis error"
|
||||
case int64:
|
||||
sname = "Redis integer"
|
||||
case []byte:
|
||||
sname = "Redis bulk string"
|
||||
case []interface{}:
|
||||
sname = "Redis array"
|
||||
default:
|
||||
sname = reflect.TypeOf(s).String()
|
||||
}
|
||||
return fmt.Errorf("cannot convert from %s to %s", sname, d.Type())
|
||||
}
|
||||
|
||||
func convertAssignBulkString(d reflect.Value, s []byte) (err error) {
|
||||
switch d.Type().Kind() {
|
||||
case reflect.Float32, reflect.Float64:
|
||||
var x float64
|
||||
x, err = strconv.ParseFloat(string(s), d.Type().Bits())
|
||||
d.SetFloat(x)
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
var x int64
|
||||
x, err = strconv.ParseInt(string(s), 10, d.Type().Bits())
|
||||
d.SetInt(x)
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
var x uint64
|
||||
x, err = strconv.ParseUint(string(s), 10, d.Type().Bits())
|
||||
d.SetUint(x)
|
||||
case reflect.Bool:
|
||||
var x bool
|
||||
x, err = strconv.ParseBool(string(s))
|
||||
d.SetBool(x)
|
||||
case reflect.String:
|
||||
d.SetString(string(s))
|
||||
case reflect.Slice:
|
||||
if d.Type().Elem().Kind() != reflect.Uint8 {
|
||||
err = cannotConvert(d, s)
|
||||
} else {
|
||||
d.SetBytes(s)
|
||||
}
|
||||
default:
|
||||
err = cannotConvert(d, s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func convertAssignInt(d reflect.Value, s int64) (err error) {
|
||||
switch d.Type().Kind() {
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
d.SetInt(s)
|
||||
if d.Int() != s {
|
||||
err = strconv.ErrRange
|
||||
d.SetInt(0)
|
||||
}
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
if s < 0 {
|
||||
err = strconv.ErrRange
|
||||
} else {
|
||||
x := uint64(s)
|
||||
d.SetUint(x)
|
||||
if d.Uint() != x {
|
||||
err = strconv.ErrRange
|
||||
d.SetUint(0)
|
||||
}
|
||||
}
|
||||
case reflect.Bool:
|
||||
d.SetBool(s != 0)
|
||||
default:
|
||||
err = cannotConvert(d, s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func convertAssignValue(d reflect.Value, s interface{}) (err error) {
|
||||
if d.Kind() != reflect.Ptr {
|
||||
if d.CanAddr() {
|
||||
d2 := d.Addr()
|
||||
if d2.CanInterface() {
|
||||
if scanner, ok := d2.Interface().(Scanner); ok {
|
||||
return scanner.RedisScan(s)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if d.CanInterface() {
|
||||
// Already a reflect.Ptr
|
||||
if d.IsNil() {
|
||||
d.Set(reflect.New(d.Type().Elem()))
|
||||
}
|
||||
if scanner, ok := d.Interface().(Scanner); ok {
|
||||
return scanner.RedisScan(s)
|
||||
}
|
||||
}
|
||||
|
||||
switch s := s.(type) {
|
||||
case []byte:
|
||||
err = convertAssignBulkString(d, s)
|
||||
case int64:
|
||||
err = convertAssignInt(d, s)
|
||||
default:
|
||||
err = cannotConvert(d, s)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func convertAssignArray(d reflect.Value, s []interface{}) error {
|
||||
if d.Type().Kind() != reflect.Slice {
|
||||
return cannotConvert(d, s)
|
||||
}
|
||||
ensureLen(d, len(s))
|
||||
for i := 0; i < len(s); i++ {
|
||||
if err := convertAssignValue(d.Index(i), s[i]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func convertAssign(d interface{}, s interface{}) (err error) {
|
||||
if scanner, ok := d.(Scanner); ok {
|
||||
return scanner.RedisScan(s)
|
||||
}
|
||||
|
||||
// Handle the most common destination types using type switches and
|
||||
// fall back to reflection for all other types.
|
||||
switch s := s.(type) {
|
||||
case nil:
|
||||
// ignore
|
||||
case []byte:
|
||||
switch d := d.(type) {
|
||||
case *string:
|
||||
*d = string(s)
|
||||
case *int:
|
||||
*d, err = strconv.Atoi(string(s))
|
||||
case *bool:
|
||||
*d, err = strconv.ParseBool(string(s))
|
||||
case *[]byte:
|
||||
*d = s
|
||||
case *interface{}:
|
||||
*d = s
|
||||
case nil:
|
||||
// skip value
|
||||
default:
|
||||
if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
|
||||
err = cannotConvert(d, s)
|
||||
} else {
|
||||
err = convertAssignBulkString(d.Elem(), s)
|
||||
}
|
||||
}
|
||||
case int64:
|
||||
switch d := d.(type) {
|
||||
case *int:
|
||||
x := int(s)
|
||||
if int64(x) != s {
|
||||
err = strconv.ErrRange
|
||||
x = 0
|
||||
}
|
||||
*d = x
|
||||
case *bool:
|
||||
*d = s != 0
|
||||
case *interface{}:
|
||||
*d = s
|
||||
case nil:
|
||||
// skip value
|
||||
default:
|
||||
if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
|
||||
err = cannotConvert(d, s)
|
||||
} else {
|
||||
err = convertAssignInt(d.Elem(), s)
|
||||
}
|
||||
}
|
||||
case string:
|
||||
switch d := d.(type) {
|
||||
case *string:
|
||||
*d = s
|
||||
case *interface{}:
|
||||
*d = s
|
||||
case nil:
|
||||
// skip value
|
||||
default:
|
||||
err = cannotConvert(reflect.ValueOf(d), s)
|
||||
}
|
||||
case []interface{}:
|
||||
switch d := d.(type) {
|
||||
case *[]interface{}:
|
||||
*d = s
|
||||
case *interface{}:
|
||||
*d = s
|
||||
case nil:
|
||||
// skip value
|
||||
default:
|
||||
if d := reflect.ValueOf(d); d.Type().Kind() != reflect.Ptr {
|
||||
err = cannotConvert(d, s)
|
||||
} else {
|
||||
err = convertAssignArray(d.Elem(), s)
|
||||
}
|
||||
}
|
||||
case Error:
|
||||
err = s
|
||||
default:
|
||||
err = cannotConvert(reflect.ValueOf(d), s)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Scan copies from src to the values pointed at by dest.
|
||||
//
|
||||
// Scan uses RedisScan if available otherwise:
|
||||
//
|
||||
// The values pointed at by dest must be an integer, float, boolean, string,
|
||||
// []byte, interface{} or slices of these types. Scan uses the standard strconv
|
||||
// package to convert bulk strings to numeric and boolean types.
|
||||
//
|
||||
// If a dest value is nil, then the corresponding src value is skipped.
|
||||
//
|
||||
// If a src element is nil, then the corresponding dest value is not modified.
|
||||
//
|
||||
// To enable easy use of Scan in a loop, Scan returns the slice of src
|
||||
// following the copied values.
|
||||
func Scan(src []interface{}, dest ...interface{}) ([]interface{}, error) {
|
||||
if len(src) < len(dest) {
|
||||
return nil, errors.New("redigo.Scan: array short")
|
||||
}
|
||||
var err error
|
||||
for i, d := range dest {
|
||||
err = convertAssign(d, src[i])
|
||||
if err != nil {
|
||||
err = fmt.Errorf("redigo.Scan: cannot assign to dest %d: %v", i, err)
|
||||
break
|
||||
}
|
||||
}
|
||||
return src[len(dest):], err
|
||||
}
|
||||
|
||||
type fieldSpec struct {
|
||||
name string
|
||||
index []int
|
||||
omitEmpty bool
|
||||
}
|
||||
|
||||
type structSpec struct {
|
||||
m map[string]*fieldSpec
|
||||
l []*fieldSpec
|
||||
}
|
||||
|
||||
func (ss *structSpec) fieldSpec(name []byte) *fieldSpec {
|
||||
return ss.m[string(name)]
|
||||
}
|
||||
|
||||
func compileStructSpec(t reflect.Type, depth map[string]int, index []int, ss *structSpec) {
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
f := t.Field(i)
|
||||
switch {
|
||||
case f.PkgPath != "" && !f.Anonymous:
|
||||
// Ignore unexported fields.
|
||||
case f.Anonymous:
|
||||
// TODO: Handle pointers. Requires change to decoder and
|
||||
// protection against infinite recursion.
|
||||
if f.Type.Kind() == reflect.Struct {
|
||||
compileStructSpec(f.Type, depth, append(index, i), ss)
|
||||
}
|
||||
default:
|
||||
fs := &fieldSpec{name: f.Name}
|
||||
tag := f.Tag.Get("redis")
|
||||
p := strings.Split(tag, ",")
|
||||
if len(p) > 0 {
|
||||
if p[0] == "-" {
|
||||
continue
|
||||
}
|
||||
if len(p[0]) > 0 {
|
||||
fs.name = p[0]
|
||||
}
|
||||
for _, s := range p[1:] {
|
||||
switch s {
|
||||
case "omitempty":
|
||||
fs.omitEmpty = true
|
||||
default:
|
||||
panic(fmt.Errorf("redigo: unknown field tag %s for type %s", s, t.Name()))
|
||||
}
|
||||
}
|
||||
}
|
||||
d, found := depth[fs.name]
|
||||
if !found {
|
||||
d = 1 << 30
|
||||
}
|
||||
switch {
|
||||
case len(index) == d:
|
||||
// At same depth, remove from result.
|
||||
delete(ss.m, fs.name)
|
||||
j := 0
|
||||
for i := 0; i < len(ss.l); i++ {
|
||||
if fs.name != ss.l[i].name {
|
||||
ss.l[j] = ss.l[i]
|
||||
j += 1
|
||||
}
|
||||
}
|
||||
ss.l = ss.l[:j]
|
||||
case len(index) < d:
|
||||
fs.index = make([]int, len(index)+1)
|
||||
copy(fs.index, index)
|
||||
fs.index[len(index)] = i
|
||||
depth[fs.name] = len(index)
|
||||
ss.m[fs.name] = fs
|
||||
ss.l = append(ss.l, fs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var (
|
||||
structSpecMutex sync.RWMutex
|
||||
structSpecCache = make(map[reflect.Type]*structSpec)
|
||||
defaultFieldSpec = &fieldSpec{}
|
||||
)
|
||||
|
||||
func structSpecForType(t reflect.Type) *structSpec {
|
||||
|
||||
structSpecMutex.RLock()
|
||||
ss, found := structSpecCache[t]
|
||||
structSpecMutex.RUnlock()
|
||||
if found {
|
||||
return ss
|
||||
}
|
||||
|
||||
structSpecMutex.Lock()
|
||||
defer structSpecMutex.Unlock()
|
||||
ss, found = structSpecCache[t]
|
||||
if found {
|
||||
return ss
|
||||
}
|
||||
|
||||
ss = &structSpec{m: make(map[string]*fieldSpec)}
|
||||
compileStructSpec(t, make(map[string]int), nil, ss)
|
||||
structSpecCache[t] = ss
|
||||
return ss
|
||||
}
|
||||
|
||||
var errScanStructValue = errors.New("redigo.ScanStruct: value must be non-nil pointer to a struct")
|
||||
|
||||
// ScanStruct scans alternating names and values from src to a struct. The
|
||||
// HGETALL and CONFIG GET commands return replies in this format.
|
||||
//
|
||||
// ScanStruct uses exported field names to match values in the response. Use
|
||||
// 'redis' field tag to override the name:
|
||||
//
|
||||
// Field int `redis:"myName"`
|
||||
//
|
||||
// Fields with the tag redis:"-" are ignored.
|
||||
//
|
||||
// Each field uses RedisScan if available otherwise:
|
||||
// Integer, float, boolean, string and []byte fields are supported. Scan uses the
|
||||
// standard strconv package to convert bulk string values to numeric and
|
||||
// boolean types.
|
||||
//
|
||||
// If a src element is nil, then the corresponding field is not modified.
|
||||
func ScanStruct(src []interface{}, dest interface{}) error {
|
||||
d := reflect.ValueOf(dest)
|
||||
if d.Kind() != reflect.Ptr || d.IsNil() {
|
||||
return errScanStructValue
|
||||
}
|
||||
d = d.Elem()
|
||||
if d.Kind() != reflect.Struct {
|
||||
return errScanStructValue
|
||||
}
|
||||
ss := structSpecForType(d.Type())
|
||||
|
||||
if len(src)%2 != 0 {
|
||||
return errors.New("redigo.ScanStruct: number of values not a multiple of 2")
|
||||
}
|
||||
|
||||
for i := 0; i < len(src); i += 2 {
|
||||
s := src[i+1]
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
name, ok := src[i].([]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("redigo.ScanStruct: key %d not a bulk string value", i)
|
||||
}
|
||||
fs := ss.fieldSpec(name)
|
||||
if fs == nil {
|
||||
continue
|
||||
}
|
||||
if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
|
||||
return fmt.Errorf("redigo.ScanStruct: cannot assign field %s: %v", fs.name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var (
|
||||
errScanSliceValue = errors.New("redigo.ScanSlice: dest must be non-nil pointer to a struct")
|
||||
)
|
||||
|
||||
// ScanSlice scans src to the slice pointed to by dest. The elements the dest
|
||||
// slice must be integer, float, boolean, string, struct or pointer to struct
|
||||
// values.
|
||||
//
|
||||
// Struct fields must be integer, float, boolean or string values. All struct
|
||||
// fields are used unless a subset is specified using fieldNames.
|
||||
func ScanSlice(src []interface{}, dest interface{}, fieldNames ...string) error {
|
||||
d := reflect.ValueOf(dest)
|
||||
if d.Kind() != reflect.Ptr || d.IsNil() {
|
||||
return errScanSliceValue
|
||||
}
|
||||
d = d.Elem()
|
||||
if d.Kind() != reflect.Slice {
|
||||
return errScanSliceValue
|
||||
}
|
||||
|
||||
isPtr := false
|
||||
t := d.Type().Elem()
|
||||
if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct {
|
||||
isPtr = true
|
||||
t = t.Elem()
|
||||
}
|
||||
|
||||
if t.Kind() != reflect.Struct {
|
||||
ensureLen(d, len(src))
|
||||
for i, s := range src {
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
if err := convertAssignValue(d.Index(i), s); err != nil {
|
||||
return fmt.Errorf("redigo.ScanSlice: cannot assign element %d: %v", i, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
ss := structSpecForType(t)
|
||||
fss := ss.l
|
||||
if len(fieldNames) > 0 {
|
||||
fss = make([]*fieldSpec, len(fieldNames))
|
||||
for i, name := range fieldNames {
|
||||
fss[i] = ss.m[name]
|
||||
if fss[i] == nil {
|
||||
return fmt.Errorf("redigo.ScanSlice: ScanSlice bad field name %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if len(fss) == 0 {
|
||||
return errors.New("redigo.ScanSlice: no struct fields")
|
||||
}
|
||||
|
||||
n := len(src) / len(fss)
|
||||
if n*len(fss) != len(src) {
|
||||
return errors.New("redigo.ScanSlice: length not a multiple of struct field count")
|
||||
}
|
||||
|
||||
ensureLen(d, n)
|
||||
for i := 0; i < n; i++ {
|
||||
d := d.Index(i)
|
||||
if isPtr {
|
||||
if d.IsNil() {
|
||||
d.Set(reflect.New(t))
|
||||
}
|
||||
d = d.Elem()
|
||||
}
|
||||
for j, fs := range fss {
|
||||
s := src[i*len(fss)+j]
|
||||
if s == nil {
|
||||
continue
|
||||
}
|
||||
if err := convertAssignValue(d.FieldByIndex(fs.index), s); err != nil {
|
||||
return fmt.Errorf("redigo.ScanSlice: cannot assign element %d to field %s: %v", i*len(fss)+j, fs.name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Args is a helper for constructing command arguments from structured values.
|
||||
type Args []interface{}
|
||||
|
||||
// Add returns the result of appending value to args.
|
||||
func (args Args) Add(value ...interface{}) Args {
|
||||
return append(args, value...)
|
||||
}
|
||||
|
||||
// AddFlat returns the result of appending the flattened value of v to args.
|
||||
//
|
||||
// Maps are flattened by appending the alternating keys and map values to args.
|
||||
//
|
||||
// Slices are flattened by appending the slice elements to args.
|
||||
//
|
||||
// Structs are flattened by appending the alternating names and values of
|
||||
// exported fields to args. If v is a nil struct pointer, then nothing is
|
||||
// appended. The 'redis' field tag overrides struct field names. See ScanStruct
|
||||
// for more information on the use of the 'redis' field tag.
|
||||
//
|
||||
// Other types are appended to args as is.
|
||||
func (args Args) AddFlat(v interface{}) Args {
|
||||
rv := reflect.ValueOf(v)
|
||||
switch rv.Kind() {
|
||||
case reflect.Struct:
|
||||
args = flattenStruct(args, rv)
|
||||
case reflect.Slice:
|
||||
for i := 0; i < rv.Len(); i++ {
|
||||
args = append(args, rv.Index(i).Interface())
|
||||
}
|
||||
case reflect.Map:
|
||||
for _, k := range rv.MapKeys() {
|
||||
args = append(args, k.Interface(), rv.MapIndex(k).Interface())
|
||||
}
|
||||
case reflect.Ptr:
|
||||
if rv.Type().Elem().Kind() == reflect.Struct {
|
||||
if !rv.IsNil() {
|
||||
args = flattenStruct(args, rv.Elem())
|
||||
}
|
||||
} else {
|
||||
args = append(args, v)
|
||||
}
|
||||
default:
|
||||
args = append(args, v)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
func flattenStruct(args Args, v reflect.Value) Args {
|
||||
ss := structSpecForType(v.Type())
|
||||
for _, fs := range ss.l {
|
||||
fv := v.FieldByIndex(fs.index)
|
||||
if fs.omitEmpty {
|
||||
var empty = false
|
||||
switch fv.Kind() {
|
||||
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
|
||||
empty = fv.Len() == 0
|
||||
case reflect.Bool:
|
||||
empty = !fv.Bool()
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
empty = fv.Int() == 0
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
|
||||
empty = fv.Uint() == 0
|
||||
case reflect.Float32, reflect.Float64:
|
||||
empty = fv.Float() == 0
|
||||
case reflect.Interface, reflect.Ptr:
|
||||
empty = fv.IsNil()
|
||||
}
|
||||
if empty {
|
||||
continue
|
||||
}
|
||||
}
|
||||
args = append(args, fs.name, fv.Interface())
|
||||
}
|
||||
return args
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
// Copyright 2012 Gary Burd
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License"): you may
|
||||
// not use this file except in compliance with the License. You may obtain
|
||||
// a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
||||
// License for the specific language governing permissions and limitations
|
||||
// under the License.
|
||||
|
||||
package redis
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Script encapsulates the source, hash and key count for a Lua script. See
|
||||
// http://redis.io/commands/eval for information on scripts in Redis.
|
||||
type Script struct {
|
||||
keyCount int
|
||||
src string
|
||||
hash string
|
||||
}
|
||||
|
||||
// NewScript returns a new script object. If keyCount is greater than or equal
|
||||
// to zero, then the count is automatically inserted in the EVAL command
|
||||
// argument list. If keyCount is less than zero, then the application supplies
|
||||
// the count as the first value in the keysAndArgs argument to the Do, Send and
|
||||
// SendHash methods.
|
||||
func NewScript(keyCount int, src string) *Script {
|
||||
h := sha1.New()
|
||||
io.WriteString(h, src)
|
||||
return &Script{keyCount, src, hex.EncodeToString(h.Sum(nil))}
|
||||
}
|
||||
|
||||
func (s *Script) args(spec string, keysAndArgs []interface{}) []interface{} {
|
||||
var args []interface{}
|
||||
if s.keyCount < 0 {
|
||||
args = make([]interface{}, 1+len(keysAndArgs))
|
||||
args[0] = spec
|
||||
copy(args[1:], keysAndArgs)
|
||||
} else {
|
||||
args = make([]interface{}, 2+len(keysAndArgs))
|
||||
args[0] = spec
|
||||
args[1] = s.keyCount
|
||||
copy(args[2:], keysAndArgs)
|
||||
}
|
||||
return args
|
||||
}
|
||||
|
||||
// Hash returns the script hash.
|
||||
func (s *Script) Hash() string {
|
||||
return s.hash
|
||||
}
|
||||
|
||||
// Do evaluates the script. Under the covers, Do optimistically evaluates the
|
||||
// script using the EVALSHA command. If the command fails because the script is
|
||||
// not loaded, then Do evaluates the script using the EVAL command (thus
|
||||
// causing the script to load).
|
||||
func (s *Script) Do(c Conn, keysAndArgs ...interface{}) (interface{}, error) {
|
||||
v, err := c.Do("EVALSHA", s.args(s.hash, keysAndArgs)...)
|
||||
if e, ok := err.(Error); ok && strings.HasPrefix(string(e), "NOSCRIPT ") {
|
||||
v, err = c.Do("EVAL", s.args(s.src, keysAndArgs)...)
|
||||
}
|
||||
return v, err
|
||||
}
|
||||
|
||||
// SendHash evaluates the script without waiting for the reply. The script is
|
||||
// evaluated with the EVALSHA command. The application must ensure that the
|
||||
// script is loaded by a previous call to Send, Do or Load methods.
|
||||
func (s *Script) SendHash(c Conn, keysAndArgs ...interface{}) error {
|
||||
return c.Send("EVALSHA", s.args(s.hash, keysAndArgs)...)
|
||||
}
|
||||
|
||||
// Send evaluates the script without waiting for the reply.
|
||||
func (s *Script) Send(c Conn, keysAndArgs ...interface{}) error {
|
||||
return c.Send("EVAL", s.args(s.src, keysAndArgs)...)
|
||||
}
|
||||
|
||||
// Load loads the script without evaluating it.
|
||||
func (s *Script) Load(c Conn) error {
|
||||
_, err := c.Do("SCRIPT", "LOAD", s.src)
|
||||
return err
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
kind: pipeline
|
||||
type: docker
|
||||
name: gopay
|
||||
|
||||
clone:
|
||||
depth: 1
|
||||
|
||||
platform:
|
||||
os: linux
|
||||
arch: amd64
|
||||
|
||||
steps:
|
||||
- name: helloworld
|
||||
pull: if-not-exists
|
||||
image: hello-world
|
||||
|
||||
- name: ci_1.16
|
||||
pull: if-not-exists
|
||||
image: golang:1.16
|
||||
environment:
|
||||
GO111MODULE: "on"
|
||||
GOPROXY: "https://goproxy.cn,direct"
|
||||
GOSUMDB: "off"
|
||||
CGO_ENABLED: "0"
|
||||
GOOS: "linux"
|
||||
depends_on:
|
||||
- helloworld
|
||||
commands:
|
||||
- go version
|
||||
- go env
|
||||
- go mod tidy
|
||||
- go test ./...
|
||||
|
||||
trigger:
|
||||
branch:
|
||||
- main
|
||||
event:
|
||||
- push
|
||||
- pull_request
|
||||
- tag
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
/.idea
|
||||
|
||||
.vscode
|
||||
|
||||
settings.json
|
||||
|
||||
vendor
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2019 Jerry
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
<div align=center><img width="240" height="240" alt="Logo was Loading Faild!" src="https://raw.githubusercontent.com/go-pay/gopay/main/logo.png"/></div>
|
||||
|
||||
# GoPay
|
||||
|
||||
### 微信、支付宝、PayPal、QQ 的 Golang 版本SDK
|
||||
|
||||
[](https://github.com/iGoogle-ink)
|
||||
[](https://github.com/go-pay/gopay/fork)
|
||||
|
||||
[](https://golang.google.cn)
|
||||
[](https://pkg.go.dev/github.com/go-pay/gopay)
|
||||
[](https://cloud.drone.io/go-pay/gopay)
|
||||
[](https://github.com/go-pay/gopay/releases)
|
||||
[](https://www.apache.org/licenses/LICENSE-2.0)
|
||||
[](https://github.com/go-pay/gopay)
|
||||
|
||||
---
|
||||
|
||||
- #### 近期计划:
|
||||
|
||||
> 将 gopay 库中,非支付相关的一些接口方法独立出去另外的 sdk 库,在 go-pay 组织下新建 `wechat-sdk` 和 `alipay-sdk` 两个项目,分别实现各个平台相关接口方法,优先进行 `wechat-sdk` 开发。
|
||||
|
||||
> 微信小程序或公众号相关接口方法:已从 `微信v2` 移步替换成 `github.com/go-pay/wechat-sdk`
|
||||
|
||||
<br>
|
||||
|
||||
# 一、安装
|
||||
|
||||
```bash
|
||||
go get -u github.com/go-pay/gopay
|
||||
```
|
||||
|
||||
#### 查看 GoPay 版本
|
||||
|
||||
[版本更新记录](https://github.com/go-pay/gopay/blob/main/release_note.txt)
|
||||
|
||||
```go
|
||||
import (
|
||||
"github.com/go-pay/gopay"
|
||||
"github.com/go-pay/gopay/pkg/xlog"
|
||||
)
|
||||
|
||||
func main() {
|
||||
xlog.Info("GoPay Version: ", gopay.Version)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
<br>
|
||||
|
||||
# 二、文档目录
|
||||
|
||||
> ### 点击查看不同支付方式的使用文档。方便的话,请留下您认可的小星星,十分感谢!
|
||||
|
||||
* #### [Alipay](https://github.com/go-pay/gopay/blob/main/doc/alipay.md)
|
||||
* #### [Wechat](https://github.com/go-pay/gopay/blob/main/doc/wechat_v3.md)
|
||||
* #### [QQ](https://github.com/go-pay/gopay/blob/main/doc/qq.md)
|
||||
* #### [Paypal](https://github.com/go-pay/gopay/blob/main/doc/paypal.md)
|
||||
* #### [Apple](https://github.com/go-pay/gopay/blob/main/doc/apple.md)
|
||||
|
||||
---
|
||||
|
||||
<br>
|
||||
|
||||
# 三、其他说明
|
||||
|
||||
* 各支付方式接入,请仔细查看 `xxx_test.go` 使用方式
|
||||
* `gopay/wechat/v3/client_test.go`
|
||||
* `gopay/alipay/client_test.go`
|
||||
* `gopay/qq/client_test.go`
|
||||
* `gopay/paypal/client_test.go`
|
||||
* `gopay/apple/verify_test.go`
|
||||
* 或 examples
|
||||
* 有问题请加QQ群(加群验证答案:gopay),或加微信好友拉群。在此,非常感谢提出宝贵意见和反馈问题的同志们!
|
||||
* 开发过程中,请尽量使用正式环境,1分钱测试法!
|
||||
|
||||
QQ群:
|
||||
<img width="280" height="280" src="https://raw.githubusercontent.com/go-pay/gopay/main/qq_gopay.png"/>
|
||||
加微信拉群:
|
||||
<img width="280" height="280" src="https://raw.githubusercontent.com/go-pay/gopay/main/wechat_jerry.png"/>
|
||||
|
||||
---
|
||||
|
||||
<br>
|
||||
|
||||
## 赞赏多少是您的心意,感谢支持!
|
||||
|
||||
微信赞赏码: <img width="200" height="200" src="https://raw.githubusercontent.com/go-pay/gopay/main/zanshang.png"/>
|
||||
支付宝赞助码: <img width="200" height="200" src="https://raw.githubusercontent.com/go-pay/gopay/main/zanshang_zfb.png"/>
|
||||
|
||||
## License
|
||||
|
||||
```
|
||||
Copyright 2019 Jerry
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
```
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 34 KiB |
+242
@@ -0,0 +1,242 @@
|
||||
package gopay
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/go-pay/gopay/pkg/util"
|
||||
)
|
||||
|
||||
type BodyMap map[string]interface{}
|
||||
|
||||
type xmlMapMarshal struct {
|
||||
XMLName xml.Name
|
||||
Value interface{} `xml:",cdata"`
|
||||
}
|
||||
|
||||
type xmlMapUnmarshal struct {
|
||||
XMLName xml.Name
|
||||
Value string `xml:",cdata"`
|
||||
}
|
||||
|
||||
// 设置参数
|
||||
func (bm BodyMap) Set(key string, value interface{}) BodyMap {
|
||||
bm[key] = value
|
||||
return bm
|
||||
}
|
||||
|
||||
func (bm BodyMap) SetBodyMap(key string, value func(b BodyMap)) BodyMap {
|
||||
_bm := make(BodyMap)
|
||||
value(_bm)
|
||||
bm[key] = _bm
|
||||
return bm
|
||||
}
|
||||
|
||||
// 设置 FormFile
|
||||
func (bm BodyMap) SetFormFile(key string, file *util.File) BodyMap {
|
||||
bm[key] = file
|
||||
return bm
|
||||
}
|
||||
|
||||
// 获取参数,同 GetString()
|
||||
func (bm BodyMap) Get(key string) string {
|
||||
return bm.GetString(key)
|
||||
}
|
||||
|
||||
// 获取参数转换string
|
||||
func (bm BodyMap) GetString(key string) string {
|
||||
if bm == nil {
|
||||
return NULL
|
||||
}
|
||||
value, ok := bm[key]
|
||||
if !ok {
|
||||
return NULL
|
||||
}
|
||||
v, ok := value.(string)
|
||||
if !ok {
|
||||
return convertToString(value)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
// 获取原始参数
|
||||
func (bm BodyMap) GetInterface(key string) interface{} {
|
||||
if bm == nil {
|
||||
return nil
|
||||
}
|
||||
return bm[key]
|
||||
}
|
||||
|
||||
// 删除参数
|
||||
func (bm BodyMap) Remove(key string) {
|
||||
delete(bm, key)
|
||||
}
|
||||
|
||||
// 置空BodyMap
|
||||
func (bm BodyMap) Reset() {
|
||||
for k := range bm {
|
||||
delete(bm, k)
|
||||
}
|
||||
}
|
||||
|
||||
func (bm BodyMap) JsonBody() (jb string) {
|
||||
bs, err := json.Marshal(bm)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
jb = string(bs)
|
||||
return jb
|
||||
}
|
||||
|
||||
// Unmarshal to struct or slice point
|
||||
func (bm BodyMap) Unmarshal(ptr interface{}) (err error) {
|
||||
bs, err := json.Marshal(bm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(bs, ptr)
|
||||
}
|
||||
|
||||
func (bm BodyMap) MarshalXML(e *xml.Encoder, start xml.StartElement) (err error) {
|
||||
if len(bm) == 0 {
|
||||
return nil
|
||||
}
|
||||
start.Name = xml.Name{Space: NULL, Local: "xml"}
|
||||
if err = e.EncodeToken(start); err != nil {
|
||||
return
|
||||
}
|
||||
for k := range bm {
|
||||
if v := bm.GetString(k); v != NULL {
|
||||
e.Encode(xmlMapMarshal{XMLName: xml.Name{Local: k}, Value: v})
|
||||
}
|
||||
}
|
||||
return e.EncodeToken(start.End())
|
||||
}
|
||||
|
||||
func (bm *BodyMap) UnmarshalXML(d *xml.Decoder, start xml.StartElement) (err error) {
|
||||
for {
|
||||
var e xmlMapUnmarshal
|
||||
err = d.Decode(&e)
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
bm.Set(e.XMLName.Local, e.Value)
|
||||
}
|
||||
}
|
||||
|
||||
// ("bar=baz&foo=quux") sorted by key.
|
||||
func (bm BodyMap) EncodeWeChatSignParams(apiKey string) string {
|
||||
if bm == nil {
|
||||
return NULL
|
||||
}
|
||||
var (
|
||||
buf strings.Builder
|
||||
keyList []string
|
||||
)
|
||||
for k := range bm {
|
||||
keyList = append(keyList, k)
|
||||
}
|
||||
sort.Strings(keyList)
|
||||
for _, k := range keyList {
|
||||
if v := bm.GetString(k); v != NULL {
|
||||
buf.WriteString(k)
|
||||
buf.WriteByte('=')
|
||||
buf.WriteString(v)
|
||||
buf.WriteByte('&')
|
||||
}
|
||||
}
|
||||
buf.WriteString("key")
|
||||
buf.WriteByte('=')
|
||||
buf.WriteString(apiKey)
|
||||
return buf.String()
|
||||
}
|
||||
|
||||
// ("bar=baz&foo=quux") sorted by key.
|
||||
func (bm BodyMap) EncodeAliPaySignParams() string {
|
||||
if bm == nil {
|
||||
return NULL
|
||||
}
|
||||
var (
|
||||
buf strings.Builder
|
||||
keyList []string
|
||||
)
|
||||
for k := range bm {
|
||||
keyList = append(keyList, k)
|
||||
}
|
||||
sort.Strings(keyList)
|
||||
for _, k := range keyList {
|
||||
if v := bm.GetString(k); v != NULL {
|
||||
buf.WriteString(k)
|
||||
buf.WriteByte('=')
|
||||
buf.WriteString(v)
|
||||
buf.WriteByte('&')
|
||||
}
|
||||
}
|
||||
if buf.Len() <= 0 {
|
||||
return NULL
|
||||
}
|
||||
return buf.String()[:buf.Len()-1]
|
||||
}
|
||||
|
||||
// ("bar=baz&foo=quux") sorted by key.
|
||||
func (bm BodyMap) EncodeURLParams() string {
|
||||
if bm == nil {
|
||||
return NULL
|
||||
}
|
||||
var (
|
||||
buf strings.Builder
|
||||
keys []string
|
||||
)
|
||||
for k := range bm {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
if v := bm.GetString(k); v != NULL {
|
||||
buf.WriteString(url.QueryEscape(k))
|
||||
buf.WriteByte('=')
|
||||
buf.WriteString(url.QueryEscape(v))
|
||||
buf.WriteByte('&')
|
||||
}
|
||||
}
|
||||
if buf.Len() <= 0 {
|
||||
return NULL
|
||||
}
|
||||
return buf.String()[:buf.Len()-1]
|
||||
}
|
||||
|
||||
func (bm BodyMap) CheckEmptyError(keys ...string) error {
|
||||
var emptyKeys []string
|
||||
for _, k := range keys {
|
||||
if v := bm.GetString(k); v == NULL {
|
||||
emptyKeys = append(emptyKeys, k)
|
||||
}
|
||||
}
|
||||
if len(emptyKeys) > 0 {
|
||||
return fmt.Errorf("[%w], %v", MissParamErr, strings.Join(emptyKeys, ", "))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func convertToString(v interface{}) (str string) {
|
||||
if v == nil {
|
||||
return NULL
|
||||
}
|
||||
var (
|
||||
bs []byte
|
||||
err error
|
||||
)
|
||||
if bs, err = json.Marshal(v); err != nil {
|
||||
return NULL
|
||||
}
|
||||
str = string(bs)
|
||||
return
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package gopay
|
||||
|
||||
const (
|
||||
NULL = ""
|
||||
SUCCESS = "SUCCESS"
|
||||
FAIL = "FAIL"
|
||||
OK = "OK"
|
||||
DebugOff = 0
|
||||
DebugOn = 1
|
||||
Version = "1.5.78"
|
||||
)
|
||||
|
||||
type DebugSwitch int8
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package gopay
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
MissWechatInitParamErr = errors.New("missing wechat init parameter")
|
||||
MissAlipayInitParamErr = errors.New("missing alipay init parameter")
|
||||
MissPayPalInitParamErr = errors.New("missing paypal init parameter")
|
||||
MissParamErr = errors.New("missing required parameter")
|
||||
MarshalErr = errors.New("marshal error")
|
||||
UnmarshalErr = errors.New("unmarshal error")
|
||||
SignatureErr = errors.New("signature error")
|
||||
VerifySignatureErr = errors.New("verify signature error")
|
||||
CertNotMatchErr = errors.New("cert not match error")
|
||||
GetSignDataErr = errors.New("get signature data error")
|
||||
)
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
module github.com/go-pay/gopay
|
||||
|
||||
go 1.16
|
||||
|
||||
require golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 h1:tkVvjkPTB7pnW3jnid7kNyAMPVWllTNOf/qKDze4p9o=
|
||||
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
|
||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 32 KiB |
+43
@@ -0,0 +1,43 @@
|
||||
package aes
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// AES-CBC 加密数据
|
||||
func CBCEncrypt(originData, key, iv []byte) ([]byte, error) {
|
||||
return cbcEncrypt(originData, key, iv)
|
||||
}
|
||||
|
||||
// AES-CBC 解密数据
|
||||
func CBCDecrypt(secretData, key, iv []byte) ([]byte, error) {
|
||||
return cbcDecrypt(secretData, key, iv)
|
||||
}
|
||||
|
||||
func cbcEncrypt(originData, key, iv []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
originData = PKCS7Padding(originData, block.BlockSize())
|
||||
secretData := make([]byte, len(originData))
|
||||
blockMode := cipher.NewCBCEncrypter(block, iv[:block.BlockSize()])
|
||||
blockMode.CryptBlocks(secretData, originData)
|
||||
return secretData, nil
|
||||
}
|
||||
|
||||
func cbcDecrypt(secretData, key, iv []byte) (originByte []byte, err error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
originByte = make([]byte, len(secretData))
|
||||
blockMode := cipher.NewCBCDecrypter(block, iv[:block.BlockSize()])
|
||||
blockMode.CryptBlocks(originByte, secretData)
|
||||
if len(originByte) == 0 {
|
||||
return nil, errors.New("blockMode.CryptBlocks error")
|
||||
}
|
||||
return PKCS7UnPadding(originByte), nil
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package aes
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"errors"
|
||||
)
|
||||
|
||||
// AES-ECB 加密数据
|
||||
func ECBEncrypt(originData, key []byte) ([]byte, error) {
|
||||
return ecbEncrypt(originData, key)
|
||||
}
|
||||
|
||||
// AES-ECB 解密数据
|
||||
func ECBDecrypt(secretData, key []byte) ([]byte, error) {
|
||||
return ecbDecrypt(secretData, key)
|
||||
}
|
||||
|
||||
func ecbEncrypt(originData, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
originData = PKCS7Padding(originData, block.BlockSize())
|
||||
secretData := make([]byte, len(originData))
|
||||
blockMode := newECBEncrypter(block)
|
||||
blockMode.CryptBlocks(secretData, originData)
|
||||
return secretData, nil
|
||||
}
|
||||
|
||||
func ecbDecrypt(secretData, key []byte) (originByte []byte, err error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
blockMode := newECBDecrypter(block)
|
||||
originByte = make([]byte, len(secretData))
|
||||
blockMode.CryptBlocks(originByte, secretData)
|
||||
if len(originByte) == 0 {
|
||||
return nil, errors.New("blockMode.CryptBlocks error")
|
||||
}
|
||||
return PKCS7UnPadding(originByte), nil
|
||||
}
|
||||
|
||||
// ===========
|
||||
|
||||
type ecb struct {
|
||||
b cipher.Block
|
||||
blockSize int
|
||||
}
|
||||
|
||||
func newECB(b cipher.Block) *ecb {
|
||||
return &ecb{
|
||||
b: b,
|
||||
blockSize: b.BlockSize(),
|
||||
}
|
||||
}
|
||||
|
||||
type ecbEncrypter ecb
|
||||
|
||||
// newECBEncrypter returns a BlockMode which encrypts in electronic code book
|
||||
// mode, using the given Block.
|
||||
func newECBEncrypter(b cipher.Block) cipher.BlockMode {
|
||||
return (*ecbEncrypter)(newECB(b))
|
||||
}
|
||||
|
||||
func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
|
||||
|
||||
func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
|
||||
if len(src)%x.blockSize != 0 {
|
||||
panic("crypto/cipher: input not full blocks")
|
||||
}
|
||||
if len(dst) < len(src) {
|
||||
panic("crypto/cipher: output smaller than input")
|
||||
}
|
||||
for len(src) > 0 {
|
||||
x.b.Encrypt(dst, src[:x.blockSize])
|
||||
src = src[x.blockSize:]
|
||||
dst = dst[x.blockSize:]
|
||||
}
|
||||
}
|
||||
|
||||
type ecbDecrypter ecb
|
||||
|
||||
// newECBDecrypter returns a BlockMode which decrypts in electronic code book
|
||||
// mode, using the given Block.
|
||||
func newECBDecrypter(b cipher.Block) cipher.BlockMode {
|
||||
return (*ecbDecrypter)(newECB(b))
|
||||
}
|
||||
|
||||
func (x *ecbDecrypter) BlockSize() int { return x.blockSize }
|
||||
|
||||
func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
|
||||
if len(src)%x.blockSize != 0 {
|
||||
panic("crypto/cipher: input not full blocks")
|
||||
}
|
||||
if len(dst) < len(src) {
|
||||
panic("crypto/cipher: output smaller than input")
|
||||
}
|
||||
for len(src) > 0 {
|
||||
x.b.Decrypt(dst, src[:x.blockSize])
|
||||
src = src[x.blockSize:]
|
||||
dst = dst[x.blockSize:]
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package aes
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"fmt"
|
||||
|
||||
"github.com/go-pay/gopay/pkg/util"
|
||||
)
|
||||
|
||||
// AES-GCM 加密数据
|
||||
func GCMEncrypt(originText, additional, key []byte) (nonce []byte, cipherText []byte, err error) {
|
||||
return gcmEncrypt(originText, additional, key)
|
||||
}
|
||||
|
||||
// AES-GCM 解密数据
|
||||
func GCMDecrypt(cipherText, nonce, additional, key []byte) ([]byte, error) {
|
||||
return gcmDecrypt(cipherText, nonce, additional, key)
|
||||
}
|
||||
|
||||
func gcmDecrypt(secretData, nonce, additional, key []byte) ([]byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("cipher.NewGCM(),error:%w", err)
|
||||
}
|
||||
originByte, err := gcm.Open(nil, nonce, secretData, additional)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return originByte, nil
|
||||
}
|
||||
|
||||
func gcmEncrypt(originText, additional, key []byte) ([]byte, []byte, error) {
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
nonce := []byte(util.RandomString(12))
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("cipher.NewGCM(),error:%w", err)
|
||||
}
|
||||
cipherBytes := gcm.Seal(nil, nonce, originText, additional)
|
||||
return nonce, cipherBytes, nil
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package aes
|
||||
|
||||
import "bytes"
|
||||
|
||||
// 加密填充模式(添加补全码) PKCS5Padding
|
||||
// 加密时,如果加密bytes的length不是blockSize的整数倍,需要在最后面添加填充byte
|
||||
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
|
||||
paddingCount := blockSize - len(ciphertext)%blockSize //需要padding的数目
|
||||
paddingBytes := []byte{byte(paddingCount)}
|
||||
padtext := bytes.Repeat(paddingBytes, paddingCount) //生成填充的文本
|
||||
return append(ciphertext, padtext...)
|
||||
}
|
||||
|
||||
// 解密填充模式(去除补全码) PKCS5UnPadding
|
||||
// 解密时,需要在最后面去掉加密时添加的填充byte
|
||||
func PKCS5UnPadding(origData []byte) []byte {
|
||||
length := len(origData)
|
||||
unpadding := int(origData[length-1]) //找到Byte数组最后的填充byte
|
||||
return origData[:(length - unpadding)] //只截取返回有效数字内的byte数组
|
||||
}
|
||||
|
||||
// 加密填充模式(添加补全码) PKCS5Padding
|
||||
// 加密时,如果加密bytes的length不是blockSize的整数倍,需要在最后面添加填充byte
|
||||
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
|
||||
paddingCount := blockSize - len(ciphertext)%blockSize //需要padding的数目
|
||||
paddingBytes := []byte{byte(paddingCount)}
|
||||
padtext := bytes.Repeat(paddingBytes, paddingCount) //生成填充的文本
|
||||
return append(ciphertext, padtext...)
|
||||
}
|
||||
|
||||
// 解密填充模式(去除补全码) PKCS7UnPadding
|
||||
// 解密时,需要在最后面去掉加密时添加的填充byte
|
||||
func PKCS7UnPadding(origData []byte) (bs []byte) {
|
||||
length := len(origData)
|
||||
unPaddingNumber := int(origData[length-1]) // 找到Byte数组最后的填充byte 数字
|
||||
if unPaddingNumber <= 16 {
|
||||
bs = origData[:(length - unPaddingNumber)] // 只截取返回有效数字内的byte数组
|
||||
} else {
|
||||
bs = origData
|
||||
}
|
||||
return
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package errgroup
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// A Group is a collection of goroutines working on subtasks that are part of
|
||||
// the same overall task.
|
||||
//
|
||||
// A zero Group is valid and does not cancel on error.
|
||||
type Group struct {
|
||||
err error
|
||||
wg sync.WaitGroup
|
||||
errOnce sync.Once
|
||||
|
||||
workerOnce sync.Once
|
||||
ch chan func(ctx context.Context) error
|
||||
chs []func(ctx context.Context) error
|
||||
workerNum int
|
||||
|
||||
ctx context.Context
|
||||
cancel func()
|
||||
}
|
||||
|
||||
// WithContext create a Group.
|
||||
// given function from Go will receive this context,
|
||||
func WithContext(ctx context.Context) *Group {
|
||||
return &Group{ctx: ctx}
|
||||
}
|
||||
|
||||
// WithCancel create a new Group and an associated Context derived from ctx.
|
||||
//
|
||||
// given function from Go will receive context derived from this ctx,
|
||||
// The derived Context is canceled the first time a function passed to Go
|
||||
// returns a non-nil error or the first time Wait returns, whichever occurs
|
||||
// first.
|
||||
func WithCancel(ctx context.Context) *Group {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
return &Group{ctx: ctx, cancel: cancel}
|
||||
}
|
||||
|
||||
func (g *Group) do(f func(ctx context.Context) error) {
|
||||
ctx := g.ctx
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
var err error
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
buf := make([]byte, 64<<10)
|
||||
buf = buf[:runtime.Stack(buf, false)]
|
||||
err = fmt.Errorf("errgroup: panic recovered: %s\n%s", r, buf)
|
||||
}
|
||||
if err != nil {
|
||||
g.errOnce.Do(func() {
|
||||
g.err = err
|
||||
if g.cancel != nil {
|
||||
g.cancel()
|
||||
}
|
||||
})
|
||||
}
|
||||
g.wg.Done()
|
||||
}()
|
||||
err = f(ctx)
|
||||
}
|
||||
|
||||
// GOMAXPROCS set max goroutine to work.
|
||||
func (g *Group) GOMAXPROCS(n int) {
|
||||
if n <= 0 {
|
||||
panic("errgroup: GOMAXPROCS must great than 0")
|
||||
}
|
||||
g.workerOnce.Do(func() {
|
||||
g.ch = make(chan func(context.Context) error, n)
|
||||
for i := 0; i < n; i++ {
|
||||
go func() {
|
||||
for f := range g.ch {
|
||||
g.do(f)
|
||||
}
|
||||
}()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Go calls the given function in a new goroutine.
|
||||
//
|
||||
// The first call to return a non-nil error cancels the group; its error will be
|
||||
// returned by Wait.
|
||||
func (g *Group) Go(f func(ctx context.Context) error) {
|
||||
g.wg.Add(1)
|
||||
g.workerNum++
|
||||
if g.ch != nil {
|
||||
select {
|
||||
case g.ch <- f:
|
||||
default:
|
||||
g.chs = append(g.chs, f)
|
||||
}
|
||||
return
|
||||
}
|
||||
go g.do(f)
|
||||
}
|
||||
|
||||
// Wait blocks until all function calls from the Go method have returned, then
|
||||
// returns the first non-nil error (if any) from them.
|
||||
func (g *Group) Wait() error {
|
||||
if g.ch != nil {
|
||||
for _, f := range g.chs {
|
||||
g.ch <- f
|
||||
}
|
||||
}
|
||||
g.wg.Wait()
|
||||
if g.ch != nil {
|
||||
close(g.ch) // let all receiver exit
|
||||
}
|
||||
if g.cancel != nil {
|
||||
g.cancel()
|
||||
}
|
||||
g.workerNum = 0
|
||||
return g.err
|
||||
}
|
||||
|
||||
func (g *Group) WorkNum() int {
|
||||
return g.workerNum
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package util
|
||||
|
||||
const (
|
||||
TimeLayout = "2006-01-02 15:04:05"
|
||||
TimeLayout_2 = "20060102150405"
|
||||
DateLayout = "2006-01-02"
|
||||
NULL = ""
|
||||
)
|
||||
|
||||
type File struct {
|
||||
Name string `json:"name"`
|
||||
Content []byte `json:"content"`
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// 字符串转Int
|
||||
// intStr:数字的字符串
|
||||
func String2Int(intStr string) (intNum int) {
|
||||
intNum, _ = strconv.Atoi(intStr)
|
||||
return
|
||||
}
|
||||
|
||||
// 字符串转Int64
|
||||
// intStr:数字的字符串
|
||||
func String2Int64(intStr string) (int64Num int64) {
|
||||
intNum, _ := strconv.Atoi(intStr)
|
||||
int64Num = int64(intNum)
|
||||
return
|
||||
}
|
||||
|
||||
// 字符串转Float64
|
||||
// floatStr:小数点数字的字符串
|
||||
func String2Float64(floatStr string) (floatNum float64) {
|
||||
floatNum, _ = strconv.ParseFloat(floatStr, 64)
|
||||
return
|
||||
}
|
||||
|
||||
// 字符串转Float32
|
||||
// floatStr:小数点数字的字符串
|
||||
func String2Float32(floatStr string) (floatNum float32) {
|
||||
floatNum64, _ := strconv.ParseFloat(floatStr, 32)
|
||||
floatNum = float32(floatNum64)
|
||||
return
|
||||
}
|
||||
|
||||
// Int转字符串
|
||||
// intNum:数字字符串
|
||||
func Int2String(intNum int) (intStr string) {
|
||||
intStr = strconv.Itoa(intNum)
|
||||
return
|
||||
}
|
||||
|
||||
// Int64转字符串
|
||||
// intNum:数字字符串
|
||||
func Int642String(intNum int64) (int64Str string) {
|
||||
//10, 代表10进制
|
||||
int64Str = strconv.FormatInt(intNum, 10)
|
||||
return
|
||||
}
|
||||
|
||||
// Float64转字符串
|
||||
// floatNum:float64数字
|
||||
// prec:精度位数(不传则默认float数字精度)
|
||||
func Float64ToString(floatNum float64, prec ...int) (floatStr string) {
|
||||
if len(prec) > 0 {
|
||||
floatStr = strconv.FormatFloat(floatNum, 'f', prec[0], 64)
|
||||
return
|
||||
}
|
||||
floatStr = strconv.FormatFloat(floatNum, 'f', -1, 64)
|
||||
return
|
||||
}
|
||||
|
||||
// Float32转字符串
|
||||
// floatNum:float32数字
|
||||
// prec:精度位数(不传则默认float数字精度)
|
||||
func Float32ToString(floatNum float32, prec ...int) (floatStr string) {
|
||||
if len(prec) > 0 {
|
||||
floatStr = strconv.FormatFloat(float64(floatNum), 'f', prec[0], 32)
|
||||
return
|
||||
}
|
||||
floatStr = strconv.FormatFloat(float64(floatNum), 'f', -1, 32)
|
||||
return
|
||||
}
|
||||
|
||||
// 二进制转10进制
|
||||
func BinaryToDecimal(bit string) (num int) {
|
||||
fields := strings.Split(bit, "")
|
||||
lens := len(fields)
|
||||
var tempF float64 = 0
|
||||
for i := 0; i < lens; i++ {
|
||||
floatNum := String2Float64(fields[i])
|
||||
tempF += floatNum * math.Pow(2, float64(lens-i-1))
|
||||
}
|
||||
num = int(tempF)
|
||||
return
|
||||
}
|
||||
|
||||
// BytesToString 0 拷贝转换 slice byte 为 string
|
||||
func BytesToString(b []byte) (s string) {
|
||||
_bptr := (*reflect.SliceHeader)(unsafe.Pointer(&b))
|
||||
_sptr := (*reflect.StringHeader)(unsafe.Pointer(&s))
|
||||
_sptr.Data = _bptr.Data
|
||||
_sptr.Len = _bptr.Len
|
||||
return s
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
//随机生成字符串
|
||||
func RandomString(l int) string {
|
||||
str := "0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
|
||||
bytes := []byte(str)
|
||||
var result []byte = make([]byte, 0, l)
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
for i := 0; i < l; i++ {
|
||||
result = append(result, bytes[r.Intn(len(bytes))])
|
||||
}
|
||||
return BytesToString(result)
|
||||
}
|
||||
|
||||
//随机生成纯字符串
|
||||
func RandomPureString(l int) string {
|
||||
str := "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
|
||||
bytes := []byte(str)
|
||||
var result []byte = make([]byte, 0, l)
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
for i := 0; i < l; i++ {
|
||||
result = append(result, bytes[r.Intn(len(bytes))])
|
||||
}
|
||||
return BytesToString(result)
|
||||
}
|
||||
|
||||
//随机生成数字字符串
|
||||
func RandomNumber(l int) string {
|
||||
str := "0123456789"
|
||||
bytes := []byte(str)
|
||||
var result []byte
|
||||
r := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
for i := 0; i < l; i++ {
|
||||
result = append(result, bytes[r.Intn(len(bytes))])
|
||||
}
|
||||
return BytesToString(result)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user