From 5c6458037852d38cad7638604730bf654d07b3cd Mon Sep 17 00:00:00 2001 From: hoteas Date: Sun, 13 Mar 2022 01:48:54 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=95=B4=E4=BD=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LICENSE | 22 ++++----- application.go | 6 +-- cache/cache_db.go | 8 ++-- cache/cache_memory.go | 88 +++++++++++++++++----------------- cache/cache_redis.go | 100 +++++++++++++++++++-------------------- code.go | 30 ++++++------ code/template.go | 26 +++++----- common/context_base.go | 8 ++-- common/func.go | 10 ++-- common/map.go | 80 +++++++++++++++---------------- db/hotimedb.go | 10 ++-- dri/aliyun/company.go | 68 +++++++++++++------------- dri/baidu/map.go | 10 ++-- dri/ddsms/ddsms.go | 38 +++++++-------- dri/download/download.go | 2 +- dri/rsa/deencrypt.go | 6 +-- dri/tencent/company.go | 32 +++++++++---- dri/tencent/tencent.go | 36 ++++++++++---- dri/upload/upload.go | 6 +-- example/main.go | 1 - manage/manage.go | 12 ++--- type.go | 2 +- 22 files changed, 312 insertions(+), 289 deletions(-) diff --git a/LICENSE b/LICENSE index 96e642d..7e66046 100644 --- a/LICENSE +++ b/LICENSE @@ -7,17 +7,17 @@ AND DISTRIBUTION 1. Definitions. - + "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of that 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. @@ -26,31 +26,31 @@ 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 that 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, @@ -59,7 +59,7 @@ original work of authorship. For the purposes of that 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 @@ -74,7 +74,7 @@ for the purpose of discussing and improving the Work, but excluding communicatio 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 @@ -142,7 +142,7 @@ 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, +6. Trademarks. that 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. diff --git a/application.go b/application.go index d7ccae1..4b5c85d 100644 --- a/application.go +++ b/application.go @@ -30,7 +30,7 @@ type Application struct { WebConnectLog *logrus.Logger Port string //端口号 TLSPort string //ssl访问端口号 - connectListener []func(this *Context) bool //所有的访问监听,true按原计划继续使用,false表示有监听器处理 + connectListener []func(that *Context) bool //所有的访问监听,true按原计划继续使用,false表示有监听器处理 connectDbFunc func(err ...*Error) (master, slave *sql.DB) configPath string Config Map @@ -258,12 +258,12 @@ func (that *Application) SetConfig(configPath ...string) { } // SetConnectListener 连接判断,返回true继续传输至控制层,false则停止传输 -func (that *Application) SetConnectListener(lis func(this *Context) bool) { +func (that *Application) SetConnectListener(lis func(that *Context) bool) { that.connectListener = append(that.connectListener, lis) } //网络错误 -//func (this *Application) session(w http.ResponseWriter, req *http.Request) { +//func (that *Application) session(w http.ResponseWriter, req *http.Request) { // //} diff --git a/cache/cache_db.go b/cache/cache_db.go index 4761dc2..40158a1 100644 --- a/cache/cache_db.go +++ b/cache/cache_db.go @@ -30,14 +30,14 @@ type CacheDb struct { isInit bool } -func (this *CacheDb) GetError() *Error { +func (that *CacheDb) GetError() *Error { - return this.Error + return that.Error } -func (this *CacheDb) SetError(err *Error) { - this.Error = err +func (that *CacheDb) SetError(err *Error) { + that.Error = err } func (that *CacheDb) initDbTable() { diff --git a/cache/cache_memory.go b/cache/cache_memory.go index 30d50e0..75e87c5 100644 --- a/cache/cache_memory.go +++ b/cache/cache_memory.go @@ -17,47 +17,47 @@ type CacheMemory struct { mutex *sync.RWMutex } -func (this *CacheMemory) GetError() *Error { +func (that *CacheMemory) GetError() *Error { - return this.Error + return that.Error } -func (this *CacheMemory) SetError(err *Error) { - this.Error = err +func (that *CacheMemory) SetError(err *Error) { + that.Error = err } //获取Cache键只能为string类型 -func (this *CacheMemory) get(key string) interface{} { - this.Error.SetError(nil) - if this.Map == nil { - this.Map = Map{} +func (that *CacheMemory) get(key string) interface{} { + that.Error.SetError(nil) + if that.Map == nil { + that.Map = Map{} } - if this.Map[key] == nil { + if that.Map[key] == nil { return nil } - data := this.Map.Get(key, this.Error).(cacheData) - if this.Error.GetError() != nil { + data := that.Map.Get(key, that.Error).(cacheData) + if that.Error.GetError() != nil { return nil } if data.time < time.Now().Unix() { - delete(this.Map, key) + delete(that.Map, key) return nil } return data.data } -func (this *CacheMemory) refreshMap() { +func (that *CacheMemory) refreshMap() { go func() { - this.mutex.Lock() - defer this.mutex.Unlock() - for key, v := range this.Map { + that.mutex.Lock() + defer that.mutex.Unlock() + for key, v := range that.Map { data := v.(cacheData) if data.time <= time.Now().Unix() { - delete(this.Map, key) + delete(that.Map, key) } } @@ -66,15 +66,15 @@ func (this *CacheMemory) refreshMap() { } //key value ,时间为时间戳 -func (this *CacheMemory) set(key string, value interface{}, time int64) { - this.Error.SetError(nil) +func (that *CacheMemory) set(key string, value interface{}, time int64) { + that.Error.SetError(nil) var data cacheData - if this.Map == nil { - this.Map = Map{} + if that.Map == nil { + that.Map = Map{} } - dd := this.Map[key] + dd := that.Map[key] if dd == nil { data = cacheData{} @@ -85,74 +85,74 @@ func (this *CacheMemory) set(key string, value interface{}, time int64) { data.time = time data.data = value - this.Map.Put(key, data) + that.Map.Put(key, data) } -func (this *CacheMemory) delete(key string) { +func (that *CacheMemory) delete(key string) { del := strings.Index(key, "*") //如果通配删除 if del != -1 { key = Substr(key, 0, del) - for k, _ := range this.Map { + for k, _ := range that.Map { if strings.Index(k, key) != -1 { - delete(this.Map, k) + delete(that.Map, k) } } } else { - delete(this.Map, key) + delete(that.Map, key) } } -func (this *CacheMemory) Cache(key string, data ...interface{}) *Obj { +func (that *CacheMemory) Cache(key string, data ...interface{}) *Obj { x := RandX(1, 100000) if x > 99950 { - this.refreshMap() + that.refreshMap() } - if this.mutex == nil { - this.mutex = &sync.RWMutex{} + if that.mutex == nil { + that.mutex = &sync.RWMutex{} } reData := &Obj{Data: nil} if len(data) == 0 { - this.mutex.RLock() - reData.Data = this.get(key) - this.mutex.RUnlock() + that.mutex.RLock() + reData.Data = that.get(key) + that.mutex.RUnlock() return reData } tim := time.Now().Unix() if len(data) == 1 && data[0] == nil { - this.mutex.Lock() - this.delete(key) - this.mutex.Unlock() + that.mutex.Lock() + that.delete(key) + that.mutex.Unlock() return reData } if len(data) == 1 { - tim = tim + this.TimeOut + tim = tim + that.TimeOut } if len(data) == 2 { - this.Error.SetError(nil) - tempt := ObjToInt64(data[1], this.Error) + that.Error.SetError(nil) + tempt := ObjToInt64(data[1], that.Error) if tempt > tim { tim = tempt - } else if this.Error.GetError() == nil { + } else if that.Error.GetError() == nil { tim = tim + tempt } } - this.mutex.Lock() - this.set(key, data[0], tim) - this.mutex.Unlock() + that.mutex.Lock() + that.set(key, data[0], tim) + that.mutex.Unlock() return reData } diff --git a/cache/cache_redis.go b/cache/cache_redis.go index 9d005ae..d62a702 100644 --- a/cache/cache_redis.go +++ b/cache/cache_redis.go @@ -20,65 +20,65 @@ type CacheRedis struct { *Error } -func (this *CacheRedis) GetError() *Error { +func (that *CacheRedis) GetError() *Error { - return this.Error + return that.Error } -func (this *CacheRedis) SetError(err *Error) { - this.Error = err +func (that *CacheRedis) SetError(err *Error) { + that.Error = err } //唯一标志 -func (this *CacheRedis) GetTag() int64 { +func (that *CacheRedis) GetTag() int64 { - if this.tag == int64(0) { - this.tag = time.Now().UnixNano() + if that.tag == int64(0) { + that.tag = time.Now().UnixNano() } - return this.tag + return that.tag } -func (this *CacheRedis) reCon() bool { +func (that *CacheRedis) reCon() bool { var err error - this.conn, err = redis.Dial("tcp", this.Host+":"+ObjToStr(this.Port)) + that.conn, err = redis.Dial("tcp", that.Host+":"+ObjToStr(that.Port)) if err != nil { - this.conn = nil - this.Error.SetError(err) + that.conn = nil + that.Error.SetError(err) return false } - if this.Pwd != "" { - _, err = this.conn.Do("AUTH", this.Pwd) + if that.Pwd != "" { + _, err = that.conn.Do("AUTH", that.Pwd) if err != nil { - this.conn = nil - this.Error.SetError(err) + that.conn = nil + that.Error.SetError(err) return false } } return true } -func (this *CacheRedis) del(key string) { +func (that *CacheRedis) del(key string) { del := strings.Index(key, "*") if del != -1 { - val, err := redis.Strings(this.conn.Do("KEYS", key)) + val, err := redis.Strings(that.conn.Do("KEYS", key)) if err != nil { return } - this.conn.Send("MULTI") + that.conn.Send("MULTI") for i, _ := range val { - this.conn.Send("DEL", val[i]) + that.conn.Send("DEL", val[i]) } - this.conn.Do("EXEC") + that.conn.Do("EXEC") } else { - _, err := this.conn.Do("DEL", key) + _, err := that.conn.Do("DEL", key) if err != nil { - this.Error.SetError(err) - _, err = this.conn.Do("PING") + that.Error.SetError(err) + _, err = that.conn.Do("PING") if err != nil { - if this.reCon() { - _, err = this.conn.Do("DEL", key) + if that.reCon() { + _, err = that.conn.Do("DEL", key) } } } @@ -86,32 +86,32 @@ func (this *CacheRedis) del(key string) { } //key value ,时间为时间戳 -func (this *CacheRedis) set(key string, value string, time int64) { - _, err := this.conn.Do("SET", key, value, "EX", ObjToStr(time)) +func (that *CacheRedis) set(key string, value string, time int64) { + _, err := that.conn.Do("SET", key, value, "EX", ObjToStr(time)) if err != nil { - this.Error.SetError(err) - _, err = this.conn.Do("PING") + that.Error.SetError(err) + _, err = that.conn.Do("PING") if err != nil { - if this.reCon() { - _, err = this.conn.Do("SET", key, value, "EX", ObjToStr(time)) + if that.reCon() { + _, err = that.conn.Do("SET", key, value, "EX", ObjToStr(time)) } } } } -func (this *CacheRedis) get(key string) *Obj { +func (that *CacheRedis) get(key string) *Obj { reData := &Obj{} var err error - reData.Data, err = redis.String(this.conn.Do("GET", key)) + reData.Data, err = redis.String(that.conn.Do("GET", key)) if err != nil { reData.Data = nil if !strings.Contains(err.Error(), "nil returned") { - this.Error.SetError(err) - _, err = this.conn.Do("PING") + that.Error.SetError(err) + _, err = that.conn.Do("PING") if err != nil { - if this.reCon() { - reData.Data, err = redis.String(this.conn.Do("GET", key)) + if that.reCon() { + reData.Data, err = redis.String(that.conn.Do("GET", key)) } } @@ -121,10 +121,10 @@ func (this *CacheRedis) get(key string) *Obj { return reData } -func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj { +func (that *CacheRedis) Cache(key string, data ...interface{}) *Obj { reData := &Obj{} - if this.conn == nil { - re := this.reCon() + if that.conn == nil { + re := that.reCon() if !re { return reData } @@ -132,38 +132,38 @@ func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj { //查询缓存 if len(data) == 0 { - reData = this.get(key) + reData = that.get(key) return reData } tim := int64(0) //删除缓存 if len(data) == 1 && data[0] == nil { - this.del(key) + that.del(key) return reData } //添加缓存 if len(data) == 1 { - if this.TimeOut == 0 { - //this.Time = Config.GetInt64("cacheShortTime") + if that.TimeOut == 0 { + //that.Time = Config.GetInt64("cacheShortTime") } - tim += this.TimeOut + tim += that.TimeOut } if len(data) == 2 { - this.Error.SetError(nil) - tempt := ObjToInt64(data[1], this.Error) + that.Error.SetError(nil) + tempt := ObjToInt64(data[1], that.Error) if tempt > tim { tim = tempt - } else if this.GetError() == nil { + } else if that.GetError() == nil { tim = tim + tempt } } - this.set(key, ObjToStr(data[0]), tim) + that.set(key, ObjToStr(data[0]), tim) return reData diff --git a/code.go b/code.go index a3140a3..84b8726 100644 --- a/code.go +++ b/code.go @@ -166,29 +166,29 @@ var TptProject = Proj{ }, }, "hotime": Ctr{ - "login": func(this *Context) { - hotimeName := this.RouterString[0] - name := this.Req.FormValue("name") - password := this.Req.FormValue("password") + "login": func(that *Context) { + hotimeName := that.RouterString[0] + name := that.Req.FormValue("name") + password := that.Req.FormValue("password") if name == "" || password == "" { - this.Display(3, "参数不足") + that.Display(3, "参数不足") return } - user := this.Db.Get(hotimeName, "*", Map{"AND": Map{"OR": Map{"name": name, "phone": name}, "password": Md5(password)}}) + user := that.Db.Get(hotimeName, "*", Map{"AND": Map{"OR": Map{"name": name, "phone": name}, "password": Md5(password)}}) if user == nil { - this.Display(5, "登录失败") + that.Display(5, "登录失败") return } - this.Session(hotimeName+"_id", user.GetCeilInt("id")) - this.Session(hotimeName+"_name", name) + that.Session(hotimeName+"_id", user.GetCeilInt("id")) + that.Session(hotimeName+"_name", name) delete(user, "password") - this.Display(0, user) + that.Display(0, user) }, - "logout": func(this *Context) { - hotimeName := this.RouterString[0] - this.Session(hotimeName+"_id", nil) - this.Session(hotimeName+"_name", nil) - this.Display(0, "退出登录成功") + "logout": func(that *Context) { + hotimeName := that.RouterString[0] + that.Session(hotimeName+"_id", nil) + that.Session(hotimeName+"_name", nil) + that.Display(0, "退出登录成功") }, "info": func(that *Context) { hotimeName := that.RouterString[0] diff --git a/code/template.go b/code/template.go index f1e6202..c990950 100644 --- a/code/template.go +++ b/code/template.go @@ -14,26 +14,26 @@ var Project = Proj{ //"user": UserCtr, {{tablesCtr}} "hotime":Ctr{ - "login": func(this *Context) { - name := this.Req.FormValue("name") - password := this.Req.FormValue("password") + "login": func(that *Context) { + name := that.Req.FormValue("name") + password := that.Req.FormValue("password") if name == "" || password == "" { - this.Display(3, "参数不足") + that.Display(3, "参数不足") return } - user := this.Db.Get("admin", "*", Map{"AND": Map{"OR":Map{"name": name,"phone":name}, "password": Md5(password)}}) + user := that.Db.Get("admin", "*", Map{"AND": Map{"OR":Map{"name": name,"phone":name}, "password": Md5(password)}}) if user == nil { - this.Display(5, "登录失败") + that.Display(5, "登录失败") return } - this.Session("admin_id", user.GetCeilInt("id")) - this.Session("admin_name", name) - this.Display(0, this.SessionId) + that.Session("admin_id", user.GetCeilInt("id")) + that.Session("admin_name", name) + that.Display(0, that.SessionId) }, - "logout": func(this *Context) { - this.Session("admin_id", nil) - this.Session("admin_name", nil) - this.Display(0, "退出登录成功") + "logout": func(that *Context) { + that.Session("admin_id", nil) + that.Session("admin_name", nil) + that.Display(0, "退出登录成功") }, "info": func(that *Context) { data := that.Db.Get("admin", "*", Map{"id": that.Session("admin_id").ToCeilInt()}) diff --git a/common/context_base.go b/common/context_base.go index c940467..0a4667f 100644 --- a/common/context_base.go +++ b/common/context_base.go @@ -9,10 +9,10 @@ type ContextBase struct { } //唯一标志 -func (this *ContextBase) GetTag() string { +func (that *ContextBase) GetTag() string { - if this.tag == "" { - this.tag = ObjToStr(time.Now().Unix()) + ":" + ObjToStr(Random()) + if that.tag == "" { + that.tag = ObjToStr(time.Now().Unix()) + ":" + ObjToStr(Random()) } - return this.tag + return that.tag } diff --git a/common/func.go b/common/func.go index 92c4d71..054b34f 100644 --- a/common/func.go +++ b/common/func.go @@ -36,7 +36,7 @@ func StrFirstToUpper(str string) string { return strings.ToUpper(first) + other } -//相似度计算 ld compares two strings and returns the levenshtein distance between them. +// StrLd 相似度计算 ld compares two strings and returns the levenshtein distance between them. func StrLd(s, t string, ignoreCase bool) int { if ignoreCase { s = strings.ToLower(s) @@ -142,7 +142,7 @@ func Md5(req string) string { return hex.EncodeToString(cipherStr) } -//随机数 +// Rand 随机数 func Rand(count int) int { res := Random() for i := 0; i < count; i++ { @@ -167,7 +167,7 @@ func Random() float64 { } -//随机数范围 +// RandX 随机数范围 func RandX(small int, max int) int { res := 0 //随机对象 @@ -219,7 +219,7 @@ func RandX(small int, max int) int { // GetDb() //} -//复制返回数组 +// DeepCopyMap 复制返回数组 func DeepCopyMap(value interface{}) interface{} { if valueMap, ok := value.(Map); ok { newMap := make(Map) @@ -278,7 +278,7 @@ func DeepCopyMap(value interface{}) interface{} { // } //} -//浮点数四舍五入保留小数 +// Round 浮点数四舍五入保留小数 func Round(f float64, n int) float64 { pow10_n := math.Pow10(n) return math.Trunc((f+0.5/pow10_n)*pow10_n) / pow10_n diff --git a/common/map.go b/common/map.go index 640e731..eeadeb8 100644 --- a/common/map.go +++ b/common/map.go @@ -10,108 +10,108 @@ import ( type Map map[string]interface{} //获取string -func (this Map) GetString(key string, err ...*Error) string { +func (that Map) GetString(key string, err ...*Error) string { if len(err) != 0 { err[0].SetError(nil) } - return ObjToStr((this)[key]) + return ObjToStr((that)[key]) } -func (this *Map) Pointer() *Map { +func (that *Map) Pointer() *Map { - return this + return that } //增加接口 -func (this Map) Put(key string, value interface{}) { - //if this==nil{ - // this=Map{} +func (that Map) Put(key string, value interface{}) { + //if that==nil{ + // that=Map{} //} - this[key] = value + that[key] = value } //删除接口 -func (this Map) Delete(key string) { - delete(this, key) +func (that Map) Delete(key string) { + delete(that, key) } //获取Int -func (this Map) GetInt(key string, err ...*Error) int { - v := ObjToInt((this)[key], err...) +func (that Map) GetInt(key string, err ...*Error) int { + v := ObjToInt((that)[key], err...) return v } //获取Int -func (this Map) GetInt64(key string, err ...*Error) int64 { - v := ObjToInt64((this)[key], err...) +func (that Map) GetInt64(key string, err ...*Error) int64 { + v := ObjToInt64((that)[key], err...) return v } //获取向上取整Int64 -func (this Map) GetCeilInt64(key string, err ...*Error) int64 { - v := ObjToCeilInt64((this)[key], err...) +func (that Map) GetCeilInt64(key string, err ...*Error) int64 { + v := ObjToCeilInt64((that)[key], err...) return v } //获取向上取整Int -func (this Map) GetCeilInt(key string, err ...*Error) int { - v := ObjToCeilInt((this)[key], err...) +func (that Map) GetCeilInt(key string, err ...*Error) int { + v := ObjToCeilInt((that)[key], err...) return v } //获取向上取整float64 -func (this Map) GetCeilFloat64(key string, err ...*Error) float64 { - v := ObjToCeilFloat64((this)[key], err...) +func (that Map) GetCeilFloat64(key string, err ...*Error) float64 { + v := ObjToCeilFloat64((that)[key], err...) return v } //获取Float64 -func (this Map) GetFloat64(key string, err ...*Error) float64 { +func (that Map) GetFloat64(key string, err ...*Error) float64 { - v := ObjToFloat64((this)[key], err...) + v := ObjToFloat64((that)[key], err...) return v } -func (this Map) GetSlice(key string, err ...*Error) Slice { +func (that Map) GetSlice(key string, err ...*Error) Slice { //var v Slice - v := ObjToSlice((this)[key], err...) + v := ObjToSlice((that)[key], err...) return v } -func (this Map) GetBool(key string, err ...*Error) bool { +func (that Map) GetBool(key string, err ...*Error) bool { //var v Slice - v := ObjToBool((this)[key], err...) + v := ObjToBool((that)[key], err...) return v } -func (this Map) GetMap(key string, err ...*Error) Map { +func (that Map) GetMap(key string, err ...*Error) Map { //var data Slice - v := ObjToMap((this)[key], err...) + v := ObjToMap((that)[key], err...) return v } -func (this Map) Get(key string, err ...*Error) interface{} { +func (that Map) Get(key string, err ...*Error) interface{} { - if v, ok := (this)[key]; ok { + if v, ok := (that)[key]; ok { return v } e := errors.New("没有存储key及对应的数据") @@ -124,10 +124,10 @@ func (this Map) Get(key string, err ...*Error) interface{} { } //请传递指针过来 -func (this Map) ToStruct(stct interface{}) { +func (that Map) ToStruct(stct interface{}) { data := reflect.ValueOf(stct).Elem() - for k, v := range this { + for k, v := range that { ks := StrFirstToUpper(k) dkey := data.FieldByName(ks) if !dkey.IsValid() { @@ -135,13 +135,13 @@ func (this Map) ToStruct(stct interface{}) { } switch dkey.Type().String() { case "int": - dkey.SetInt(this.GetInt64(k)) + dkey.SetInt(that.GetInt64(k)) case "int64": - dkey.Set(reflect.ValueOf(this.GetInt64(k))) + dkey.Set(reflect.ValueOf(that.GetInt64(k))) case "float64": - dkey.Set(reflect.ValueOf(this.GetFloat64(k))) + dkey.Set(reflect.ValueOf(that.GetFloat64(k))) case "string": - dkey.Set(reflect.ValueOf(this.GetString(k))) + dkey.Set(reflect.ValueOf(that.GetString(k))) case "interface{}": dkey.Set(reflect.ValueOf(v)) } @@ -149,13 +149,13 @@ func (this Map) ToStruct(stct interface{}) { } -func (this Map) ToJsonString() string { - return ObjToStr(this) +func (that Map) ToJsonString() string { + return ObjToStr(that) } -func (this Map) JsonToMap(jsonStr string, err ...*Error) { - e := json.Unmarshal([]byte(jsonStr), &this) +func (that Map) JsonToMap(jsonStr string, err ...*Error) { + e := json.Unmarshal([]byte(jsonStr), &that) if e != nil && len(err) != 0 { err[0].SetError(e) } diff --git a/db/hotimedb.go b/db/hotimedb.go index 8a1ea23..0900b94 100644 --- a/db/hotimedb.go +++ b/db/hotimedb.go @@ -165,7 +165,7 @@ func (that *HoTimeDB) Row(resl *sql.Rows) []Map { // ////code=0,1,2 0 backup all,1 backup data,2 backup ddl -//func (this *HoTimeDB) Backup(path string, code int) { +//func (that *HoTimeDB) Backup(path string, code int) { // var cmd *exec.Cmd // switch code { // case 0:cmd= exec.Command("mysqldump","-h"+ObjToStr(Config["dbHost"]), "-P"+ObjToStr(Config["dbPort"]),"-u"+ObjToStr(Config["dbUser"]), "-p"+ObjToStr(Config["dbPwd"]),ObjToStr(Config["dbName"])) @@ -197,7 +197,7 @@ func (that *HoTimeDB) Row(resl *sql.Rows) []Map { // //db := `` // //fmt.Println(db) // // -// //tables := this.Query("show tables") +// //tables := that.Query("show tables") // //lth := len(tables) // //if lth == 0 { // // return @@ -212,7 +212,7 @@ func (that *HoTimeDB) Row(resl *sql.Rows) []Map { // // // //for i := 0; i < lth; i++ { // // tt := tables[i]["Tables_in_"+db].(string) -// // this.backupSave(path, tt, code) +// // that.backupSave(path, tt, code) // // debug.FreeOSMemory() // //} // @@ -383,7 +383,7 @@ func (that *HoTimeDB) Exec(query string, args ...interface{}) (sql.Result, *Erro return resl, that.LastErr } -//func (this *HoTimeDB)copy(data []Map)[]Map{ +//func (that *HoTimeDB)copy(data []Map)[]Map{ // if data==nil{ // return nil // } @@ -836,7 +836,7 @@ func (that *HoTimeDB) varCond(k string, v interface{}) (string, []interface{}) { return where, res } -// this.Db.Update("user",hotime.Map{"ustate":"1"},hotime.Map{"AND":hotime.Map{"OR":hotime.Map{"uid":4,"uname":"dasda"}},"ustate":1}) +// that.Db.Update("user",hotime.Map{"ustate":"1"},hotime.Map{"AND":hotime.Map{"OR":hotime.Map{"uid":4,"uname":"dasda"}},"ustate":1}) func (that *HoTimeDB) notIn(k string, v interface{}, where string, res []interface{}) (string, []interface{}) { //where:="" //fmt.Println(reflect.ValueOf(v).Type().String()) diff --git a/dri/aliyun/company.go b/dri/aliyun/company.go index 7b91e13..d17f3fb 100644 --- a/dri/aliyun/company.go +++ b/dri/aliyun/company.go @@ -8,46 +8,48 @@ import ( //"fmt" ) -type Company struct { +type company struct { ApiCode string Url string } -func (this *Company) Init(apiCode string) { +var Company = company{} + +func (that *company) Init(apiCode string) { //"06c6a07e89dd45c88de040ee1489eef7" - this.ApiCode = apiCode - this.Url = "http://api.81api.com" + that.ApiCode = apiCode + that.Url = "http://api.81api.com" } -// GetCompanyBaseInfo 获取企业基础信息 -func (this *Company) GetCompanyOtherAll(name string) Map { +// GetCompanyOtherAll 获取企业基础信息 +func (that *company) GetCompanyOtherAll(name string) Map { res := Map{} - data, e := this.GetCompanyPatentsInfo(name) //获取专利信息 + data, e := that.GetCompanyPatentsInfo(name) //获取专利信息 if e != nil { fmt.Println(e) } else { res["PatentsInfo"] = data.GetMap("data") } - data, e = this.GetCompanyOtherCopyrightsInfo(name) //获取其他专利 + data, e = that.GetCompanyOtherCopyrightsInfo(name) //获取其他专利 if e != nil { fmt.Println(e) } else { res["OtherCopyrightsInfo"] = data.GetMap("data") } - data, e = this.GetCompanyTrademarksInfo(name) //获取商标 + data, e = that.GetCompanyTrademarksInfo(name) //获取商标 if e != nil { fmt.Println(e) } else { res["TrademarksInfo"] = data.GetMap("data") } - data, e = this.GetCompanySoftwareCopyrightsInfo(name) //获取软著 + data, e = that.GetCompanySoftwareCopyrightsInfo(name) //获取软著 if e != nil { fmt.Println(e) } else { res["SoftwareCopyrightsInfo"] = data.GetMap("data") } - data, e = this.GetCompanyProfileTags(name) //获取大数据标签 + data, e = that.GetCompanyProfileTags(name) //获取大数据标签 if e != nil { fmt.Println(e) } else { @@ -57,63 +59,63 @@ func (this *Company) GetCompanyOtherAll(name string) Map { } // GetCompanyBaseInfo 获取企业基础信息 -func (this *Company) GetCompanyBaseInfo(name string) (Map, error) { +func (that *company) GetCompanyBaseInfo(name string) (Map, error) { url := "/getCompanyBaseInfo/" - body, err := this.basePost(url, name) + body, err := that.basePost(url, name) return ObjToMap(body), err } // GetCompanyPatentsInfo 获取专利信息 -func (this *Company) GetCompanyPatentsInfo(name string) (Map, error) { +func (that *company) GetCompanyPatentsInfo(name string) (Map, error) { url := "/getCompanyPatentsInfo/" - body, err := this.basePost(url, name) + body, err := that.basePost(url, name) return ObjToMap(body), err } -// 获取商标信息 -func (this *Company) GetCompanyTrademarksInfo(name string) (Map, error) { +// GetCompanyTrademarksInfo 获取商标信息 +func (that *company) GetCompanyTrademarksInfo(name string) (Map, error) { url := "/getCompanyTrademarksInfo/" - body, err := this.basePost(url, name) + body, err := that.basePost(url, name) return ObjToMap(body), err } -// 获取软著信息 -func (this *Company) GetCompanySoftwareCopyrightsInfo(name string) (Map, error) { +// GetCompanySoftwareCopyrightsInfo 获取软著信息 +func (that *company) GetCompanySoftwareCopyrightsInfo(name string) (Map, error) { url := "/getCompanySoftwareCopyrightsInfo/" - body, err := this.basePost(url, name) + body, err := that.basePost(url, name) return ObjToMap(body), err } -// 获取其他著作信息 -func (this *Company) GetCompanyOtherCopyrightsInfo(name string) (Map, error) { +// GetCompanyOtherCopyrightsInfo 获取其他著作信息 +func (that *company) GetCompanyOtherCopyrightsInfo(name string) (Map, error) { url := "/getCompanyOtherCopyrightsInfo/" - body, err := this.basePost(url, name) + body, err := that.basePost(url, name) return ObjToMap(body), err } -// 获取大数据标签 -func (this *Company) GetCompanyProfileTags(name string) (Map, error) { +// GetCompanyProfileTags 获取大数据标签 +func (that *company) GetCompanyProfileTags(name string) (Map, error) { url := "/getCompanyProfileTags/" - body, err := this.basePost(url, name) + body, err := that.basePost(url, name) return ObjToMap(body), err } -func (this *Company) basePost(url string, name string) (string, error) { +func (that *company) basePost(url string, name string) (string, error) { client := &http.Client{} - reqest, err := http.NewRequest("GET", this.Url+url+name+"/?isRaiseErrorCode=1", nil) + reqest, err := http.NewRequest("GET", that.Url+url+name+"/?isRaiseErrorCode=1", nil) if err != nil { fmt.Println("Fatal error ", err.Error()) return "", err } - reqest.Header.Add("Authorization", "APPCODE "+this.ApiCode) + reqest.Header.Add("Authorization", "APPCODE "+that.ApiCode) response, err := client.Do(reqest) defer response.Body.Close() @@ -130,9 +132,3 @@ func (this *Company) basePost(url string, name string) (string, error) { fmt.Println(res) return res, err } - -var DefaultCompany Company - -func init() { - DefaultCompany = Company{} -} diff --git a/dri/baidu/map.go b/dri/baidu/map.go index 00ca4cb..3dd611d 100644 --- a/dri/baidu/map.go +++ b/dri/baidu/map.go @@ -12,21 +12,21 @@ type BaiduMap struct { Url string } -func (this *BaiduMap) Init(Ak string) { +func (that *BaiduMap) Init(Ak string) { //"ak=ZeT902EZvVgIoGVWEFK3osUm" - this.Ak = Ak - this.Url = "https://api.map.baidu.com/place/v2/suggestion?output=json" + "&ak=" + Ak + that.Ak = Ak + that.Url = "https://api.map.baidu.com/place/v2/suggestion?output=json" + "&ak=" + Ak //query } // GetPosition 获取定位列表 -func (this *BaiduMap) GetPosition(name string, region string) (string, error) { +func (that *BaiduMap) GetPosition(name string, region string) (string, error) { client := &http.Client{} if region == "" { region = "全国" } - reqest, err := http.NewRequest("GET", this.Url+"&query="+url.PathEscape(name)+"®ion="+url.PathEscape(region), nil) + reqest, err := http.NewRequest("GET", that.Url+"&query="+url.PathEscape(name)+"®ion="+url.PathEscape(region), nil) if err != nil { fmt.Println("Fatal error ", err.Error()) diff --git a/dri/ddsms/ddsms.go b/dri/ddsms/ddsms.go index 499c8c1..5310b25 100644 --- a/dri/ddsms/ddsms.go +++ b/dri/ddsms/ddsms.go @@ -10,29 +10,31 @@ import ( //"fmt" ) -type DDY struct { +type dingdongyun struct { ApiKey string YzmUrl string TzUrl string } -func (this *DDY) Init(apikey string) { - this.ApiKey = apikey - this.YzmUrl = "https://api.dingdongcloud.com/v2/sms/captcha/send.json" - this.TzUrl = "https://api.dingdongcloud.com/v2/sms/notice/send.json" +var DDY = dingdongyun{} + +func (that *dingdongyun) Init(apikey string) { + that.ApiKey = apikey + that.YzmUrl = "https://api.dingdongcloud.com/v2/sms/captcha/send.json" + that.TzUrl = "https://api.dingdongcloud.com/v2/sms/notice/send.json" } -//发送短信验证码 code验证码如:123456 返回true表示发送成功flase表示发送失败 -func (this *DDY) SendYZM(umoblie string, tpt string, data map[string]string) (bool, error) { +// SendYZM 发送短信验证码 code验证码如:123456 返回true表示发送成功flase表示发送失败 +func (that *dingdongyun) SendYZM(umoblie string, tpt string, data map[string]string) (bool, error) { for k, v := range data { tpt = strings.Replace(tpt, "{"+k+"}", v, -1) } - return this.send(this.YzmUrl, umoblie, tpt) + return that.send(that.YzmUrl, umoblie, tpt) } -//发送通知 -func (this *DDY) SendTz(umoblie []string, tpt string, data map[string]string) (bool, error) { +// SendTz 发送通知 +func (that *dingdongyun) SendTz(umoblie []string, tpt string, data map[string]string) (bool, error) { for k, v := range data { tpt = strings.Replace(tpt, "{"+k+"}", v, -1) } @@ -44,14 +46,14 @@ func (this *DDY) SendTz(umoblie []string, tpt string, data map[string]string) (b } umobleStr += "," + v } - return this.send(this.TzUrl, umobleStr, tpt) + return that.send(that.TzUrl, umobleStr, tpt) } //发送短信 -func (this *DDY) send(mUrl string, umoblie string, content string) (bool, error) { +func (that *dingdongyun) send(mUrl string, umoblie string, content string) (bool, error) { - data_send_sms_yzm := url.Values{"apikey": {this.ApiKey}, "mobile": {umoblie}, "content": {content}} - res, err := this.httpsPostForm(mUrl, data_send_sms_yzm) + data_send_sms_yzm := url.Values{"apikey": {that.ApiKey}, "mobile": {umoblie}, "content": {content}} + res, err := that.httpsPostForm(mUrl, data_send_sms_yzm) if err != nil && res == "" { return false, errors.New("连接错误") } @@ -73,7 +75,7 @@ func (this *DDY) send(mUrl string, umoblie string, content string) (bool, error) } //调用url发送短信的连接 -func (this *DDY) httpsPostForm(url string, data url.Values) (string, error) { +func (that *dingdongyun) httpsPostForm(url string, data url.Values) (string, error) { resp, err := http.PostForm(url, data) if err != nil { @@ -89,9 +91,3 @@ func (this *DDY) httpsPostForm(url string, data url.Values) (string, error) { return string(body), nil } - -var DefaultDDY DDY - -func init() { - DefaultDDY = DDY{} -} diff --git a/dri/download/download.go b/dri/download/download.go index 7b74339..4d84680 100644 --- a/dri/download/download.go +++ b/dri/download/download.go @@ -9,7 +9,7 @@ import ( "os" ) -//下载文件 +// Down 下载文件 func Down(url, path, name string, e ...*Error) bool { os.MkdirAll(path, os.ModeDir) diff --git a/dri/rsa/deencrypt.go b/dri/rsa/deencrypt.go index a590cfa..3a0e30c 100644 --- a/dri/rsa/deencrypt.go +++ b/dri/rsa/deencrypt.go @@ -23,7 +23,7 @@ func FileGet(path string) []byte { return buf } -//RSA加密 +// RSA_Encrypt RSA加密 // plainText 要加密的数据 // path 公钥匙文件地址 func RSA_Encrypt(plainText []byte, buf []byte) []byte { @@ -46,7 +46,7 @@ func RSA_Encrypt(plainText []byte, buf []byte) []byte { return cipherText } -//RSA解密 +// RSA_Decrypt RSA解密 // cipherText 需要解密的byte数据 // path 私钥文件路径 func RSA_Decrypt(cipherText []byte, buf []byte) []byte { @@ -97,7 +97,7 @@ func Demo() { fmt.Println(string(decrypt)) } -//生成RSA私钥和公钥,保存到文件中 +// GenerateRSAKey 生成RSA私钥和公钥,保存到文件中 // bits 证书大小 func GenerateRSAKey(bits int, path string) { //GenerateKey函数使用随机数据生成器random生成一对具有指定字位数的RSA密钥 diff --git a/dri/tencent/company.go b/dri/tencent/company.go index 1b032dc..6454a44 100644 --- a/dri/tencent/company.go +++ b/dri/tencent/company.go @@ -15,24 +15,40 @@ import ( "time" ) -func calcAuthorization(source string, secretId string, secretKey string) (auth string, datetime string, err error) { +type company struct { + secretId string + secretKey string +} + +var Company = company{} + +func (that *company) Init(secretId, secretKey string) { + // 云市场分配的密钥Id + //secretId := "xxxx" + //// 云市场分配的密钥Key + //secretKey := "xxxx" + that.secretId = secretId + that.secretKey = secretKey +} + +func (that *company) calcAuthorization(source string) (auth string, datetime string, err error) { timeLocation, _ := time.LoadLocation("Etc/GMT") datetime = time.Now().In(timeLocation).Format("Mon, 02 Jan 2006 15:04:05 GMT") signStr := fmt.Sprintf("x-date: %s\nx-source: %s", datetime, source) // hmac-sha1 - mac := hmac.New(sha1.New, []byte(secretKey)) + mac := hmac.New(sha1.New, []byte(that.secretKey)) mac.Write([]byte(signStr)) sign := base64.StdEncoding.EncodeToString(mac.Sum(nil)) auth = fmt.Sprintf("hmac id=\"%s\", algorithm=\"hmac-sha1\", headers=\"x-date x-source\", signature=\"%s\"", - secretId, sign) + that.secretId, sign) return auth, datetime, nil } -func urlencode(params map[string]string) string { +func (that *company) urlencode(params map[string]string) string { var p = gourl.Values{} for k, v := range params { p.Add(k, v) @@ -40,7 +56,7 @@ func urlencode(params map[string]string) string { return p.Encode() } -func GetCompany(secretId, secretKey, name string) Map { +func (that *company) GetCompany(name string) Map { // 云市场分配的密钥Id //secretId := "xxxx" //// 云市场分配的密钥Key @@ -48,7 +64,7 @@ func GetCompany(secretId, secretKey, name string) Map { source := "market" // 签名 - auth, datetime, _ := calcAuthorization(source, secretId, secretKey) + auth, datetime, _ := that.calcAuthorization(source) // 请求方法 method := "GET" @@ -64,13 +80,13 @@ func GetCompany(secretId, secretKey, name string) Map { // url参数拼接 url := "https://service-3jnh3ku8-1256140209.gz.apigw.tencentcs.com/release/business4/geet" if len(queryParams) > 0 { - url = fmt.Sprintf("%s?%s", url, urlencode(queryParams)) + url = fmt.Sprintf("%s?%s", url, that.urlencode(queryParams)) } bodyMethods := map[string]bool{"POST": true, "PUT": true, "PATCH": true} var body io.Reader = nil if bodyMethods[method] { - body = strings.NewReader(urlencode(bodyParams)) + body = strings.NewReader(that.urlencode(bodyParams)) headers["Content-Type"] = "application/x-www-form-urlencoded" } diff --git a/dri/tencent/tencent.go b/dri/tencent/tencent.go index cdcab4f..ebff51c 100644 --- a/dri/tencent/tencent.go +++ b/dri/tencent/tencent.go @@ -8,16 +8,32 @@ import ( ocr "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/ocr/v20181119" ) -var credential = common.NewCredential( - "AKIDOgT8cKCQksnY7yKATaYO7j9ORJzSYohP", - "GNXgjdN4czA9ya0FNMApVJzTmsmU0KSN", -) +type tencent struct { + secretId string + secretKey string + credential *common.Credential +} -func OCRCOMPANY(base64Str string) string { +var Tencent = tencent{} + +func (that *tencent) Init(secretId, secretKey string) { + // 云市场分配的密钥Id + //secretId := "xxxx" + //// 云市场分配的密钥Key + //secretKey := "xxxx" + that.secretId = secretId + that.secretKey = secretKey + that.credential = common.NewCredential( + "AKIDOgT8cKCQksnY7yKATaYO7j9ORJzSYohP", + "GNXgjdN4czA9ya0FNMApVJzTmsmU0KSN", + ) +} + +func (that *tencent) OCRCOMPANY(base64Str string) string { cpf := profile.NewClientProfile() cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com" - client, _ := ocr.NewClient(credential, "ap-guangzhou", cpf) + client, _ := ocr.NewClient(that.credential, "ap-guangzhou", cpf) request := ocr.NewBizLicenseOCRRequest() @@ -38,11 +54,11 @@ func OCRCOMPANY(base64Str string) string { return response.ToJsonString() } -func OCR(base64Str string) string { +func (that *tencent) OCR(base64Str string) string { cpf := profile.NewClientProfile() cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com" - client, _ := ocr.NewClient(credential, "ap-guangzhou", cpf) + client, _ := ocr.NewClient(that.credential, "ap-guangzhou", cpf) request := ocr.NewGeneralAccurateOCRRequest() @@ -63,11 +79,11 @@ func OCR(base64Str string) string { return response.ToJsonString() } -func Qrcode(base64Str string) string { +func (that *tencent) Qrcode(base64Str string) string { cpf := profile.NewClientProfile() cpf.HttpProfile.Endpoint = "ocr.tencentcloudapi.com" - client, _ := ocr.NewClient(credential, "ap-guangzhou", cpf) + client, _ := ocr.NewClient(that.credential, "ap-guangzhou", cpf) request := ocr.NewQrcodeOCRRequest() diff --git a/dri/upload/upload.go b/dri/upload/upload.go index 9746d00..020cab3 100644 --- a/dri/upload/upload.go +++ b/dri/upload/upload.go @@ -15,7 +15,7 @@ type Upload struct { Path string } -func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, savePath string) (string, error) { +func (that *Upload) UpFile(Request *http.Request, fieldName, savefilepath, savePath string) (string, error) { Request.ParseMultipartForm(32 << 20) var filePath string files := Request.MultipartForm.File @@ -36,7 +36,7 @@ func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, saveP data := time.Unix(int64(t), 0).Format("2006-01") path := "" if strings.EqualFold(savefilepath, "") { - path = this.Path + data + path = that.Path + data } else { path = savefilepath + data } @@ -51,7 +51,7 @@ func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, saveP } } filename := time.Unix(int64(t), 0).Format("2006-01-02-15-22-25") + ObjToStr(Rand(6)) - filePath = path + "/" + filename + this.Path + filePath = path + "/" + filename + that.Path } else { filePath = savePath } diff --git a/example/main.go b/example/main.go index 86c3cd7..7440692 100644 --- a/example/main.go +++ b/example/main.go @@ -2,7 +2,6 @@ package main import ( "code.hoteas.com/golang/hotime" - //"code.hoteas.com/golang/hotime/dri/aliyun" "fmt" "time" ) diff --git a/manage/manage.go b/manage/manage.go index 38fdbe6..a003655 100644 --- a/manage/manage.go +++ b/manage/manage.go @@ -44,17 +44,17 @@ func Run() { appIns.Run(hotime.Router{ "app": hotime.Proj{ "index": hotime.Ctr{ - "test": func(this *hotime.Context) { - fmt.Println(this.Db.GetTag()) - //x := this.Db.Action(func(db hotime.HoTimeDB) bool { + "test": func(that *hotime.Context) { + fmt.Println(that.Db.GetTag()) + //x := that.Db.Action(func(db hotime.HoTimeDB) bool { // // db.Insert("user", hotime.Map{"unickname": "dasdas"}) // // return true //}) - this.Display(0, 1) + that.Display(0, 1) }, - "websocket": func(this *hotime.Context) { + "websocket": func(that *hotime.Context) { hdler := websocket.Handler(func(ws *websocket.Conn) { for true { msg := make([]byte, 5120) @@ -73,7 +73,7 @@ func Run() { fmt.Printf("Send: %s\n", msg[:m]) } }) - hdler.ServeHTTP(this.Resp, this.Req) + hdler.ServeHTTP(that.Resp, that.Req) }, }, }, diff --git a/type.go b/type.go index ca64b9e..fc46ef6 100644 --- a/type.go +++ b/type.go @@ -5,4 +5,4 @@ type Ctr map[string]Method type Proj map[string]Ctr type Router map[string]Proj type MethodRouter map[string]Method //直接字符串关联函数 -type Method func(this *Context) +type Method func(that *Context)