From 0f29b3304e8d4a56f2b655ec2636deb65a170da9 Mon Sep 17 00:00:00 2001 From: hoteas <925970985@qq.com> Date: Thu, 20 Feb 2020 14:20:56 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E8=B7=A8=E5=9F=9F=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=EF=BC=8C=E4=BB=A5=E5=8F=8A=E5=A2=9E=E5=8A=A0=E9=85=8D?= =?UTF-8?q?=E7=BD=AE=E8=AF=B4=E6=98=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- application.go | 67 +++++++++++++++++++++++++---- cache/cache_redis.go | 74 ++++++++++++++++----------------- cache_memory.go | 1 - const.go | 9 ++-- context.go | 3 +- context_base.go | 2 +- dri/ddsms/ddsms.go | 2 - dri/download/download.go | 2 +- dri/upload/upload.go | 6 +-- error.go | 44 ++++++++++---------- example/config/confignote.json | 33 +++++++++++++++ example/main.go | 9 ++-- func.go | 23 ++++------ map.go | 4 +- obj.go | 6 +-- objtoobj.go | 32 +++++++------- session.go | 4 +- slice.go | 2 + {dri => tools}/db/auto.go | 4 +- {dri => tools}/mysql/mysql.go | 0 {dri => tools}/sqlite/sqlite.go | 0 type.go | 4 +- var.go | 68 +++++++++++++++++++++++------- 23 files changed, 255 insertions(+), 144 deletions(-) create mode 100644 example/config/confignote.json rename {dri => tools}/db/auto.go (81%) rename {dri => tools}/mysql/mysql.go (100%) rename {dri => tools}/sqlite/sqlite.go (100%) diff --git a/application.go b/application.go index 604cfe6..f7ee562 100644 --- a/application.go +++ b/application.go @@ -221,25 +221,31 @@ func (this *Application) SetConfig(configPath ...string) { //文件如果损坏则不写入配置防止配置文件数据丢失 if this.Error.GetError() == nil { - var out bytes.Buffer + var configByte bytes.Buffer - err = json.Indent(&out, []byte(this.Config.ToJsonString()), "", "\t") + err = json.Indent(&configByte, []byte(this.Config.ToJsonString()), "", "\t") //判断配置文件是否序列有变化有则修改配置,五则不变 //fmt.Println(len(btes)) - if len(btes) != 0 && out.String() == string(btes) { + if len(btes) != 0 && configByte.String() == string(btes) { return } - - err = ioutil.WriteFile(this.configPath, out.Bytes(), os.ModeAppend) - + //写入配置说明 + var configNoteByte bytes.Buffer + json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t") + ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend) + //写入配置 + err = ioutil.WriteFile(this.configPath, configByte.Bytes(), os.ModeAppend) if err != nil { os.MkdirAll(filepath.Dir(this.configPath), os.ModeDir) os.Create(this.configPath) - err = ioutil.WriteFile(this.configPath, out.Bytes(), os.ModeAppend) - + err = ioutil.WriteFile(this.configPath, configByte.Bytes(), os.ModeAppend) if err != nil { this.Error.SetError(err) } + //写入配置说明 + os.Create(filepath.Dir(this.configPath) + "/confignote.json") + ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend) + } } @@ -322,6 +328,8 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) { //url去掉参数并序列化 context.HandlerStr, context.RouterString = this.urlSer(context.HandlerStr) + //跨域设置 + CrossDomain(&context) //访问拦截true继续false暂停 connectListenerLen := len(this.connectListener) if connectListenerLen != 0 { @@ -402,3 +410,46 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) { http.ServeFile(w, req, path) } + +func CrossDomain(this *Context) { + //没有跨域设置 + if this.Config.GetString("crossDomain") == "" { + return + } + + header := this.Resp.Header() + header.Set("Access-Control-Allow-Origin", "*") + header.Set("Access-Control-Allow-Methods", "*") + header.Set("Access-Control-Allow-Credentials", "true") + header.Set("Access-Control-Expose-Headers", "*") + header.Set("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,Access-Token") + + if this.Config.GetString("crossDomain") != "*" { + header.Set("Access-Control-Allow-Origin", this.Config.GetString("crossDomain")) + return + } + + origin := this.Req.Header.Get("Origin") + if origin != "" { + header.Set("Access-Control-Allow-Origin", origin) + return + } + + refer := this.Req.Header.Get("Referer") + if refer != "" { + tempInt := 0 + lastInt := strings.IndexFunc(refer, func(r rune) bool { + if r == '/' && tempInt > 8 { + return true + } + tempInt++ + return false + }) + + if lastInt < 0 { + lastInt = len(refer) + } + refer = Substr(refer, 0, lastInt) + header.Set("Access-Control-Allow-Origin", refer) + } +} diff --git a/cache/cache_redis.go b/cache/cache_redis.go index 04536a6..c839041 100644 --- a/cache/cache_redis.go +++ b/cache/cache_redis.go @@ -1,18 +1,18 @@ package cache import ( - "time" "github.com/garyburd/redigo/redis" . "go.hoteas.com/hotime" "strings" + "time" ) type CacheRedis struct { Host string - Pwd string + Pwd string Time int64 conn redis.Conn - tag int64 + tag int64 Error } @@ -25,28 +25,28 @@ func (this *CacheRedis) GetTag() int64 { return this.tag } -func (this *CacheRedis) reCon()bool{ +func (this *CacheRedis) reCon() bool { var err error - this.conn,err=redis.Dial("tcp",this.Host) - if err!=nil{ - this.conn=nil + this.conn, err = redis.Dial("tcp", this.Host) + if err != nil { + this.conn = nil this.Error.SetError(err) return false } - _,err=this.conn.Do("AUTH",this.Pwd) - if err!=nil{ - this.conn=nil + _, err = this.conn.Do("AUTH", this.Pwd) + if err != nil { + this.conn = nil this.Error.SetError(err) return false } return true } -func (this *CacheRedis) del(key string) { - del:=strings.Index(key,"*") - if del!=-1{ +func (this *CacheRedis) del(key string) { + del := strings.Index(key, "*") + if del != -1 { val, err := redis.Strings(this.conn.Do("KEYS", key)) - if err!=nil{ + if err != nil { return } this.conn.Send("MULTI") @@ -54,14 +54,14 @@ func (this *CacheRedis) del(key string) { this.conn.Send("DEL", val[i]) } this.conn.Do("EXEC") - }else{ - _,err:=this.conn.Do("DEL",key) - if err!=nil{ + } else { + _, err := this.conn.Do("DEL", key) + if err != nil { this.Error.SetError(err) - _,err=this.conn.Do("PING") - if err!=nil{ - if this.reCon(){ - _,err=this.conn.Do("DEL",key) + _, err = this.conn.Do("PING") + if err != nil { + if this.reCon() { + _, err = this.conn.Do("DEL", key) } } } @@ -70,26 +70,25 @@ 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)) - if err!=nil{ + _, err := this.conn.Do("SET", key, value, "EX", ObjToStr(time)) + if err != nil { this.Error.SetError(err) - _,err=this.conn.Do("PING") - if err!=nil{ - if this.reCon(){ - _,err=this.conn.Do("SET",key,value,"EX",ObjToStr(time)) + _, err = this.conn.Do("PING") + if err != nil { + if this.reCon() { + _, err = this.conn.Do("SET", key, value, "EX", ObjToStr(time)) } } } } - -func (this *CacheRedis) get(key string) *Obj{ - reData:= &Obj{} +func (this *CacheRedis) get(key string) *Obj { + reData := &Obj{} var err error reData.Data, err = redis.String(this.conn.Do("GET", key)) if err != nil { - reData.Data=nil + reData.Data = nil if !strings.Contains(err.Error(), "nil returned") { this.Error.SetError(err) _, err = this.conn.Do("PING") @@ -106,17 +105,17 @@ func (this *CacheRedis) get(key string) *Obj{ } func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj { - reData:= &Obj{} - if this.conn==nil{ - re:=this.reCon() - if !re{ + reData := &Obj{} + if this.conn == nil { + re := this.reCon() + if !re { return reData } } //查询缓存 if len(data) == 0 { - reData=this.get(key) + reData = this.get(key) return reData } @@ -147,8 +146,7 @@ func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj { } } - - this.set(key,ObjToStr(data[0]),tim) + this.set(key, ObjToStr(data[0]), tim) return reData diff --git a/cache_memory.go b/cache_memory.go index 7af41d8..074e7df 100644 --- a/cache_memory.go +++ b/cache_memory.go @@ -71,7 +71,6 @@ func (this *CacheMemory) set(key string, value interface{}, time int64) { data.time = time data.data = value - this.Map.Put(key, data) } diff --git a/const.go b/const.go index bd0d2ed..cff7b89 100644 --- a/const.go +++ b/const.go @@ -1,9 +1,10 @@ package hotime const ( - LOG_FMT = 0 - LOG_NIL = 1 - LOG_FILE=2 + LOG_FMT = 0 + LOG_NIL = 1 + LOG_FILE = 2 ) + //session储存头 -const HEAD_SESSION_ADD ="session#" \ No newline at end of file +const HEAD_SESSION_ADD = "session#" diff --git a/context.go b/context.go index eb0a1d8..a393441 100644 --- a/context.go +++ b/context.go @@ -14,13 +14,12 @@ type Context struct { RouterString []string Config Map Db *HoTimeDB - RespData Map + RespData Map CacheIns SessionIns HandlerStr string //复写请求url } - //唯一标志 func (this *Context) Mtd(router [3]string) Map { this.Application.Router[router[0]][router[1]][router[2]](this) diff --git a/context_base.go b/context_base.go index 5dee7ca..b48ac20 100644 --- a/context_base.go +++ b/context_base.go @@ -4,7 +4,7 @@ import "time" type contextBase struct { Error - tag int64 + tag int64 } //唯一标志 diff --git a/dri/ddsms/ddsms.go b/dri/ddsms/ddsms.go index 0962326..0d36b52 100644 --- a/dri/ddsms/ddsms.go +++ b/dri/ddsms/ddsms.go @@ -56,8 +56,6 @@ func (this *DDY) send(mUrl string, umoblie string, content string) (bool, error) return false, errors.New("连接错误") } - - var msg interface{} err1 := json.Unmarshal([]byte(res), &msg) if err1 != nil { diff --git a/dri/download/download.go b/dri/download/download.go index 4779a16..915c169 100644 --- a/dri/download/download.go +++ b/dri/download/download.go @@ -24,7 +24,7 @@ func Down(url, path, name string) bool { } defer out.Close() resp, err := http.Get(url) - if err!=nil{ + if err != nil { return false } defer resp.Body.Close() diff --git a/dri/upload/upload.go b/dri/upload/upload.go index 4447397..9b653d9 100644 --- a/dri/upload/upload.go +++ b/dri/upload/upload.go @@ -26,7 +26,7 @@ func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, saveP fieldName = k file, _, err = Request.FormFile(fieldName) if err != nil { - return "", errors.New("上传头像失败") + return "", errors.New("上传文件失败") } } @@ -58,12 +58,12 @@ func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, saveP header, err := os.OpenFile(filePath, os.O_CREATE, 0666) if err != nil { - return "", errors.New("服务器创建头像文件失败") + return "", errors.New("服务器创建文件失败") } _, err = io.Copy(header, file) if err != nil { - return "", errors.New("服务器复制头像文件失败") + return "", errors.New("服务器复制文件失败") } return filePath, nil diff --git a/error.go b/error.go index 1aef5e2..fcedb1e 100644 --- a/error.go +++ b/error.go @@ -2,7 +2,6 @@ package hotime import ( "log" - ) //框架层处理错误 @@ -10,33 +9,32 @@ type Error struct { err error } -func(this *Error)GetError()error{ +func (this *Error) GetError() error { return this.err } -func(this *Error)SetError(err error,loglevel ...int){ +func (this *Error) SetError(err error, loglevel ...int) { - - this.err=nil - if err==nil{ - this.err=err - return - } - - lev:=Config.GetInt("logLevel") - - if len(loglevel)!=0{ - lev=loglevel[0] - } - - if lev==LOG_FMT{ - log.Println(err) - } - if lev==LOG_FILE{ - log.Println(err) - } - this.err=err + this.err = nil + if err == nil { + this.err = err return + } + + lev := Config.GetInt("logLevel") + + if len(loglevel) != 0 { + lev = loglevel[0] + } + + if lev == LOG_FMT { + log.Println(err) + } + if lev == LOG_FILE { + log.Println(err) + } + this.err = err + return } diff --git a/example/config/confignote.json b/example/config/confignote.json new file mode 100644 index 0000000..b6cd50a --- /dev/null +++ b/example/config/confignote.json @@ -0,0 +1,33 @@ +{ + "cacheLongTime": "两级缓存,长缓存存储时间60 * 60 * 24 * 30,一般为数据库或者redis缓存", + "cacheShortTime": "两级缓存,短缓存存储时间60 * 60 * 2,一般为内存缓存", + "crossDomain": "跨域设置,空字符串为不开启,*为开启所有网站允许跨域,http://www.baidu.com为指定域允许跨域", + "dbCached": "是否开启数据库缓存0为关闭,其他开启", + "dbHost": "数据库ip地址默认127.0.0.1", + "dbName": "数据库名称,sqlite为文件路径比如a/x.db", + "dbPort": "数据库端口", + "dbPwd": "数据库密码", + "dbType": "如果使用自动数据库配置,请设置此项,手动配置数据库不需要,目前支持mysql,sqlite", + "dbUser": "数据库用户名", + "debug": "是否开启debug模式,0关闭,其他开启,debug模式下日志展示更全", + "defFile": "默认访问文件,默认访问index.html或者index.htm文件", + "error": { + "1": "内部系统异常,在环境配置,文件访问权限等基础运行环境条件不足造成严重错误时使用", + "2": "访问权限异常,没有登录或者登录异常等时候使用", + "3": "请求参数异常,request参数不满足要求,比如参数不足,参数类型错误,参数不满足要求等时候使用", + "4": "数据处理异常,数据库操作或者三方请求返回的结果非正常结果,比如数据库突然中断等时候使用", + "5": "数据结果异常,一般用于无法给出response要求的格式要求下使用,比如response需要的是string格式但你只能提供int数据时", + "注释": "web服务内置错误提示,自定义异常建议10开始" + }, + "logLevel": "日志等级,0打印,1关闭,2,记录到文件", + "modeRouterStrict": "路由严格模式false,为大小写忽略必须匹配,true必须大小写匹配", + "port": "web服务开启Http端口,0为不启用http服务", + "redisHost": "需要使用redis服务时配置,默认服务ip:127.0.0.1", + "redisPort": "需要使用redis服务时配置,默认服务端口:6379", + "redisPwd": "需要使用redis服务时配置,默认服务密码:123456", + "sessionName": "设置session的cookie名默认HOTIME", + "tlsCert": "https证书", + "tlsKey": "https密钥", + "tlsPort": "web服务https端口,0为不启用https服务", + "tpt": "静态文件目录,默认为程序目录下tpt目录" +} \ No newline at end of file diff --git a/example/main.go b/example/main.go index 3ab4be8..8dd7006 100644 --- a/example/main.go +++ b/example/main.go @@ -2,10 +2,9 @@ package main import ( "code.hoteas.com/hoteas/hotime" - "code.hoteas.com/hoteas/hotime/dri/mysql" + "code.hoteas.com/hoteas/hotime/tools/db" "fmt" "strings" - //"go.hoteas.com/hotime/cache" "golang.org/x/net/websocket" "time" @@ -32,8 +31,10 @@ func main() { //ca.Cache("xyzo","dasdas") //ca.Cache("xyz*",nil) //fmt.Println(ca.Cache("xyzm").Data) - - mysql.SetDB(&appIns) + //mysql + //mysql.SetDB(&appIns) + //自动选择数据库 + db.SetDB(&appIns) //appIns.SetConnectDB(func(err ...*hotime.Error) *sql.DB { // query := appIns.Config.GetString("dbUser") + ":" + appIns.Config.GetString("dbPwd") + diff --git a/func.go b/func.go index 7f36bbd..5b7f1b7 100644 --- a/func.go +++ b/func.go @@ -7,9 +7,6 @@ import ( "strings" ) - - - //安全锁 //func SafeMutex(tag int, f func() interface{}) interface{} { // @@ -27,7 +24,6 @@ import ( // return res //} - //字符串首字符大写 func StrFirstToUpper(str string) string { if len(str) == 0 { @@ -119,22 +115,20 @@ func Rand(count int) int { return ObjToInt(res) } func Random() float64 { - v:=float64(0); - m:=float64(0.1); - for i:=0;i<15;i++{ - facter:=map[int]int{4:1,9:1,2:1,3:1,1:1,7:1,0:1,5:1,6:1,8:1,} - for k,_:= range facter{ + v := float64(0) + m := float64(0.1) + for i := 0; i < 15; i++ { + facter := map[int]int{4: 1, 9: 1, 2: 1, 3: 1, 1: 1, 7: 1, 0: 1, 5: 1, 6: 1, 8: 1} + for k, _ := range facter { - v=v+float64(k)*m + v = v + float64(k)*m break } - m=m*0.1 + m = m * 0.1 } - return v - } //随机数范围 @@ -146,7 +140,7 @@ func RandX(small int, max int) int { } for { - res = ObjToInt(Random()*float64(max+1)) + res = ObjToInt(Random() * float64(max+1)) if res >= small { break } @@ -305,4 +299,3 @@ func Round(f float64, n int) float64 { // CacheMemIns.Init(Config["cacheConfig"].(Map)["memory"].(CacheConfg).Time) // CacheDBIns.Init(Config["cacheConfig"].(Map)["db"].(CacheConfg).Time) //} - diff --git a/map.go b/map.go index 5d02738..1d9751d 100644 --- a/map.go +++ b/map.go @@ -46,7 +46,6 @@ func (this Map) GetInt(key string, err ...*Error) int { } - //获取Int func (this Map) GetInt64(key string, err ...*Error) int64 { v := ObjToInt64((this)[key], err...) @@ -60,18 +59,21 @@ func (this Map) GetCeilInt64(key string, err ...*Error) int64 { return v } + //获取向上取整Int func (this Map) GetCeilInt(key string, err ...*Error) int { v := ObjToCeilInt((this)[key], err...) return v } + //获取向上取整float64 func (this Map) GetCeilFloat64(key string, err ...*Error) float64 { v := ObjToCeilFloat64((this)[key], err...) return v } + //获取Float64 func (this Map) GetFloat64(key string, err ...*Error) float64 { diff --git a/obj.go b/obj.go index 857e2a3..da6488c 100644 --- a/obj.go +++ b/obj.go @@ -60,14 +60,13 @@ func (this *Obj) ToSlice(err ...Error) Slice { return ObjToSlice(this.Data, &this.Error) } -func (this *Obj)ToMapArray(err ...Error)[]Map{ +func (this *Obj) ToMapArray(err ...Error) []Map { if len(err) != 0 { this.Error = err[0] } return ObjToMapArray(this.Data, &this.Error) } - func (this *Obj) ToObj() interface{} { return this.Data @@ -82,6 +81,7 @@ func (this *Obj) ToCeilInt64(err ...*Error) int64 { return v } + //获取向上取整Int func (this *Obj) ToCeilInt(err ...*Error) int { if len(err) != 0 { @@ -90,4 +90,4 @@ func (this *Obj) ToCeilInt(err ...*Error) int { v := ObjToCeilInt(this.Data, err...) return v -} \ No newline at end of file +} diff --git a/objtoobj.go b/objtoobj.go index 18fa279..d9f5419 100644 --- a/objtoobj.go +++ b/objtoobj.go @@ -3,8 +3,8 @@ package hotime import ( "encoding/json" "errors" - "strconv" "math" + "strconv" ) //仅限于hotime.Slice @@ -49,12 +49,11 @@ func ObjToMap(obj interface{}, e ...*Error) Map { return v } - func ObjToMapArray(obj interface{}, e ...*Error) []Map { - s:=ObjToSlice(obj,e...) - res:=[]Map{} - for i:=0;i