整个包结构重构

This commit is contained in:
hoteas 2021-05-24 07:27:41 +08:00
parent 77ded19742
commit 9bc930750d
23 changed files with 245 additions and 202 deletions

View File

@ -1,6 +1,9 @@
package hotime
import (
. "./cache"
. "./common"
. "./db"
"bytes"
"database/sql"
"encoding/json"
@ -17,7 +20,7 @@ import (
type Application struct {
MethodRouter
Router
contextBase
ContextBase
Log logrus.Logger
Port string //端口号
TLSPort string //ssl访问端口号
@ -50,14 +53,14 @@ func (this *Application) Run(router Router) {
}
//防止手动设置session误伤
if this.sessionShort == nil && this.sessionLong == nil {
if this.connectDbFunc == nil {
this.SetSession(CacheIns(&CacheMemory{}), nil)
} else {
this.SetSession(CacheIns(&CacheMemory{}), CacheIns(&CacheDb{Db: &this.Db, Time: this.Config.GetInt64("cacheLongTime")}))
}
}
//if this.sessionShort == nil && this.sessionLong == nil {
// if this.connectDbFunc == nil {
// this.SetSession(CacheIns(&CacheMemory{}), nil)
// } else {
// this.SetSession(CacheIns(&CacheMemory{}), CacheIns(&CacheDb{Db: &this.Db, Time: this.Config.GetInt64("cacheLongTime")}))
// }
//
//}
this.Router = router
//重新设置MethodRouter//直达路由
@ -105,7 +108,7 @@ func (this *Application) Run(router Router) {
defer func() {
if err := recover(); err != nil {
//this.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
logFmt(err, 2, LOG_ERROR)
LogFmt(err, 2, LOG_ERROR)
this.Run(router)
}
@ -125,7 +128,7 @@ func (this *Application) Run(router Router) {
//启动服务
this.Server.Addr = ":" + this.Port
err := this.Server.ListenAndServe()
logFmt(err, 2)
LogFmt(err, 2)
ch <- 1
}()
@ -139,20 +142,20 @@ func (this *Application) Run(router Router) {
//启动服务
this.Server.Addr = ":" + this.TLSPort
err := this.Server.ListenAndServeTLS(this.Config.GetString("tlsCert"), this.Config.GetString("tlsKey"))
logFmt(err, 2)
LogFmt(err, 2)
ch <- 2
}()
}
if ObjToCeilInt(this.Port) == 0 && ObjToCeilInt(this.TLSPort) == 0 {
logFmt("没有端口启用", 2, LOG_INFO)
LogFmt("没有端口启用", 2, LOG_INFO)
return
}
value := <-ch
logFmt("启动服务失败 : "+ObjToStr(value), 2, LOG_ERROR)
LogFmt("启动服务失败 : "+ObjToStr(value), 2, LOG_ERROR)
}
//启动实例
@ -211,7 +214,7 @@ func (this *Application) SetConfig(configPath ...string) {
Config[k] = v //系统配置
}
} else {
logFmt("配置文件不存在,或者配置出错,使用缺省默认配置", 2)
LogFmt("配置文件不存在,或者配置出错,使用缺省默认配置", 2)
}
@ -320,7 +323,7 @@ func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
this.crossDomain(&context)
//是否展示日志
if this.Config.GetInt("connectLogShow") != 0 {
logFmt(Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))+" "+context.HandlerStr, 0, LOG_INFO)
LogFmt(Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))+" "+context.HandlerStr, 0, LOG_INFO)
}
//访问拦截true继续false暂停
@ -446,6 +449,7 @@ func (this *Application) crossDomain(context *Context) {
header.Set("Access-Control-Allow-Origin", refer)
}
}
func Init(config string) Application {
appIns := Application{}
//手动模式,
@ -454,3 +458,55 @@ func Init(config string) Application {
//appIns.SetCache()
return appIns
}
//后期整改
func SetDB(appIns *Application) {
db := appIns.Config.GetMap("db")
dbSqlite := db.GetMap("sqlite")
dbMysql := db.GetMap("mysql")
if db != nil && dbSqlite != nil {
SetSqliteDB(appIns, dbSqlite)
}
if db != nil && dbMysql != nil {
SetMysqlDB(appIns, dbMysql)
}
}
func SetMysqlDB(appIns *Application, config Map) {
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
//master数据库配置
query := config.GetString("user") + ":" + config.GetString("password") +
"@tcp(" + config.GetString("host") + ":" + config.GetString("port") + ")/" + config.GetString("name") + "?charset=utf8"
DB, e := sql.Open("mysql", query)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
master = DB
//slave数据库配置
configSlave := config.GetMap("slave")
if configSlave != nil {
query := configSlave.GetString("user") + ":" + configSlave.GetString("password") +
"@tcp(" + config.GetString("host") + ":" + configSlave.GetString("port") + ")/" + configSlave.GetString("name") + "?charset=utf8"
DB1, e := sql.Open("mysql", query)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
slave = DB1
}
return master, slave
//return DB
})
appIns.Db.Type = "mysql"
}
func SetSqliteDB(appIns *Application, config Map) {
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
db, e := sql.Open("sqlite3", config.GetString("path"))
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
master = db
return master, slave
})
appIns.Db.Type = "sqlite"
}

View File

@ -1,4 +1,8 @@
package hotime
package cache
import (
. "../common"
)
type HoTimeCache struct {

View File

@ -1,15 +1,28 @@
package hotime
package cache
import (
. "../common"
"database/sql"
"encoding/json"
"strings"
"time"
)
type HoTimeDBInterface interface {
Query(query string, args ...interface{}) []Map
Exec(query string, args ...interface{}) (sql.Result, Error)
Get(table string, qu ...interface{}) Map
Select(table string, qu ...interface{}) []Map
Delete(table string, data map[string]interface{}) int64
Update(table string, data Map, where Map) int64
Insert(table string, data map[string]interface{}) int64
GetType() string
}
type CacheDb struct {
Time int64
Db *HoTimeDB
contextBase
Db HoTimeDBInterface
ContextBase
isInit bool
}
@ -17,7 +30,7 @@ func (this *CacheDb) initDbTable() {
if this.isInit {
return
}
if this.Db.Type == "mysql" {
if this.Db.GetType() == "mysql" {
dbNames := this.Db.Query("SELECT DATABASE()")
@ -38,7 +51,7 @@ func (this *CacheDb) initDbTable() {
}
if this.Db.Type == "sqlite" {
if this.Db.GetType() == "sqlite" {
res := this.Db.Query(`select * from sqlite_master where type = 'table' and name = 'cached'`)
if len(res) != 0 {
@ -126,7 +139,7 @@ func (this *CacheDb) Cache(key string, data ...interface{}) *Obj {
if len(data) == 1 {
if this.Time == 0 {
this.Time = Config.GetInt64("cacheLongTime")
//this.Time = Config.GetInt64("cacheLongTime")
}
tim += this.Time
}

View File

@ -1,6 +1,7 @@
package hotime
package cache
import (
. "../common"
"strings"
"sync"
"time"
@ -9,7 +10,7 @@ import (
type CacheMemory struct {
Time int64
Map
contextBase
ContextBase
mutex *sync.RWMutex
}
@ -120,7 +121,7 @@ func (this *CacheMemory) Cache(key string, data ...interface{}) *Obj {
if len(data) == 1 {
if this.Time == 0 {
this.Time = Config.GetInt64("cacheShortTime")
//this.Time = Config.GetInt64("cacheShortTime")
}
tim = tim + this.Time

View File

@ -1,6 +1,7 @@
package hotime
package cache
import (
. "../common"
"github.com/garyburd/redigo/redis"
"strings"
"time"
@ -128,7 +129,7 @@ func (this *CacheRedis) Cache(key string, data ...interface{}) *Obj {
if len(data) == 1 {
if this.Time == 0 {
this.Time = Config.GetInt64("cacheShortTime")
//this.Time = Config.GetInt64("cacheShortTime")
}
tim += this.Time

18
cache/type.go vendored Normal file
View File

@ -0,0 +1,18 @@
package cache
import (
. "../common"
)
type CacheIns interface {
//set(key string, value interface{}, time int64)
//get(key string) interface{}
//delete(key string)
Cache(key string, data ...interface{}) *Obj
}
//单条缓存数据
type cacheData struct {
time int64
data interface{}
}

View File

@ -1,4 +1,4 @@
package hotime
package common
type LOG_MODE int

View File

@ -1,14 +1,14 @@
package hotime
package common
import "time"
type contextBase struct {
type ContextBase struct {
Error
tag int64
}
//唯一标志
func (this *contextBase) GetTag() int64 {
func (this *ContextBase) GetTag() int64 {
if this.tag == int64(0) {
this.tag = time.Now().UnixNano()

View File

@ -1,4 +1,4 @@
package hotime
package common
//框架层处理错误
type Error struct {

View File

@ -1,15 +1,11 @@
package hotime
package common
import (
"crypto/md5"
"encoding/hex"
"fmt"
"math"
"os"
"path/filepath"
"runtime"
"strings"
"time"
)
//安全锁
@ -29,80 +25,84 @@ import (
// return res
//}
func LogError(logMsg interface{}) {
logFmt(fmt.Sprintln(logMsg), 2, LOG_ERROR)
}
func LogWarn(logMsg interface{}) {
logFmt(fmt.Sprintln(logMsg), 2, LOG_WARN)
}
func LogInfo(logMsg ...interface{}) {
logFmt(fmt.Sprintln(logMsg), 2, LOG_INFO)
}
//func LogError(logMsg interface{}) {
//
// logFmt(fmt.Sprintln(logMsg), 2, LOG_ERROR)
//}
//func LogWarn(logMsg interface{}) {
//
// logFmt(fmt.Sprintln(logMsg), 2, LOG_WARN)
//}
//func LogInfo(logMsg ...interface{}) {
//
// logFmt(fmt.Sprintln(logMsg), 2, LOG_INFO)
//}
//
//func LogFmt(logMsg interface{}, loglevel ...LOG_MODE) {
//
// logFmt(logMsg, 2, loglevel...)
//}
//
////日志打印以及存储到文件
//func logFmt(logMsg interface{}, printLevel int, loglevel ...LOG_MODE) {
//
// if Config.GetInt("logLevel") == int(LOG_NIL) {
// return
// }
//
// lev := LOG_INFO
// if len(loglevel) != 0 {
// lev = loglevel[0]
// }
// gofile := ""
//
// if Config.GetInt("debug") != 0 && printLevel != 0 {
// _, file, line, ok := runtime.Caller(printLevel)
// if ok {
// gofile = " " + file + ":" + ObjToStr(line)
// }
// }
//
// logStr := ""
//
// if lev == LOG_INFO {
// logStr = "info:"
// }
// if printLevel == 0 {
// logStr = "connect:"
// }
//
// if lev == LOG_WARN {
// logStr = "warn:"
// }
//
// if lev == LOG_ERROR {
// logStr = "error:"
// }
//
// logStr = fmt.Sprintln(time.Now().Format("2006/01/02 15:04:05"), logStr, logMsg, gofile)
// //打印日志
// fmt.Print(logStr)
// //不需要存储到文件
// if Config.GetString("logFile") == "" {
// return
// }
// //存储到文件
// logFilePath := time.Now().Format(Config.GetString("logFile"))
//
// os.MkdirAll(filepath.Dir(logFilePath), os.ModeAppend)
// //os.Create(logFilePath)
// f, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE, 0644)
// if err != nil {
// return
// }
// f.Write([]byte(logStr))
// f.Close()
//
//}
//日志打印以及存储到文件
func logFmt(logMsg interface{}, printLevel int, loglevel ...LOG_MODE) {
if Config.GetInt("logLevel") == int(LOG_NIL) {
return
}
lev := LOG_INFO
if len(loglevel) != 0 {
lev = loglevel[0]
}
gofile := ""
if Config.GetInt("debug") != 0 && printLevel != 0 {
_, file, line, ok := runtime.Caller(printLevel)
if ok {
gofile = " " + file + ":" + ObjToStr(line)
}
}
logStr := ""
if lev == LOG_INFO {
logStr = "info:"
}
if printLevel == 0 {
logStr = "connect:"
}
if lev == LOG_WARN {
logStr = "warn:"
}
if lev == LOG_ERROR {
logStr = "error:"
}
logStr = fmt.Sprintln(time.Now().Format("2006/01/02 15:04:05"), logStr, logMsg, gofile)
//打印日志
fmt.Print(logStr)
//不需要存储到文件
if Config.GetString("logFile") == "" {
return
}
//存储到文件
logFilePath := time.Now().Format(Config.GetString("logFile"))
os.MkdirAll(filepath.Dir(logFilePath), os.ModeAppend)
//os.Create(logFilePath)
f, err := os.OpenFile(logFilePath, os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return
}
f.Write([]byte(logStr))
f.Close()
func LogFmt(logMsg interface{}, printLevel int, loglevel ...LOG_MODE) {
fmt.Println(logMsg)
}
//字符串首字符大写

View File

@ -1,4 +1,4 @@
package hotime
package common
import (
"encoding/json"

View File

@ -1,9 +1,9 @@
package hotime
package common
//对象封装方便取用
type Obj struct {
Data interface{}
contextBase
ContextBase
}
func (this *Obj) Put(data interface{}) {

View File

@ -1,4 +1,4 @@
package hotime
package common
import (
"encoding/json"

View File

@ -1,4 +1,4 @@
package hotime
package common
import (
"errors"

View File

@ -1,13 +1,15 @@
package hotime
import (
. "./cache"
. "./common"
. "./db"
"encoding/json"
"errors"
"net/http"
)
type Context struct {
contextBase
ContextBase
Resp http.ResponseWriter
Req *http.Request
Application *Application
@ -37,7 +39,7 @@ func (this *Context) Display(statu int, data interface{}) {
tpe := this.Config.GetMap("error").GetString(ObjToStr(statu))
if tpe == "" {
logFmt(errors.New("找不到对应的错误码"), 2, LOG_WARN)
//logFmt(errors.New("找不到对应的错误码"), 2, LOG_WARN)
}
temp["type"] = tpe

View File

@ -1,6 +1,8 @@
package hotime
package db
import (
"../cache"
. "../common"
"database/sql"
"encoding/json"
"errors"
@ -11,8 +13,8 @@ import (
type HoTimeDB struct {
*sql.DB
contextBase
CacheIns
ContextBase
cache.CacheIns
Type string
DBCached bool
LastQuery string
@ -30,6 +32,11 @@ func (this *HoTimeDB) SetConnect(connect func(err ...*Error) (master, slave *sql
this.InitDb()
}
//设置数据库配置连接
func (this *HoTimeDB) GetType() string {
return this.Type
}
//事务如果action返回true则执行成功false则回滚
func (this *HoTimeDB) Action(action func(db HoTimeDB) bool) bool {
db := HoTimeDB{DB: this.DB, CacheIns: this.CacheIns, DBCached: this.DBCached}
@ -928,7 +935,7 @@ func (this *HoTimeDB) Insert(table string, data map[string]interface{}) int64 {
id := int64(0)
if err.GetError() == nil && res != nil {
id, this.LastErr.err = res.LastInsertId()
//id, this.LastErr.err = res.LastInsertId()
}

View File

@ -1,58 +0,0 @@
package hotime
import (
"database/sql"
_ "github.com/go-sql-driver/mysql"
_ "github.com/mattn/go-sqlite3"
)
func SetDB(appIns *Application) {
db := appIns.Config.GetMap("db")
dbSqlite := db.GetMap("sqlite")
dbMysql := db.GetMap("mysql")
if db != nil && dbSqlite != nil {
SetSqliteDB(appIns, dbSqlite)
}
if db != nil && dbMysql != nil {
SetMysqlDB(appIns, dbMysql)
}
}
func SetMysqlDB(appIns *Application, config Map) {
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
//master数据库配置
query := config.GetString("user") + ":" + config.GetString("password") +
"@tcp(" + config.GetString("host") + ":" + config.GetString("port") + ")/" + config.GetString("name") + "?charset=utf8"
DB, e := sql.Open("mysql", query)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
master = DB
//slave数据库配置
configSlave := config.GetMap("slave")
if configSlave != nil {
query := configSlave.GetString("user") + ":" + configSlave.GetString("password") +
"@tcp(" + config.GetString("host") + ":" + configSlave.GetString("port") + ")/" + configSlave.GetString("name") + "?charset=utf8"
DB1, e := sql.Open("mysql", query)
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
slave = DB1
}
return master, slave
//return DB
})
appIns.Db.Type = "mysql"
}
func SetSqliteDB(appIns *Application, config Map) {
appIns.SetConnectDB(func(err ...*Error) (master, slave *sql.DB) {
db, e := sql.Open("sqlite3", config.GetString("path"))
if e != nil && len(err) != 0 {
err[0].SetError(e)
}
master = db
return master, slave
})
appIns.Db.Type = "sqlite"
}

View File

@ -1,8 +1,8 @@
package download
import (
. "../../common"
"bytes"
"code.hoteas.com/golang/hotime"
"io"
"io/ioutil"
"net/http"
@ -13,11 +13,11 @@ import (
func Down(url, path, name string) bool {
os.MkdirAll(path, os.ModeDir)
if hotime.Substr(path, len(path)-1, len(path)) != "/" {
if Substr(path, len(path)-1, len(path)) != "/" {
path = path + "/"
}
out, err := os.Create(path + name)
e := hotime.Error{}
e := Error{}
if err != nil {
e.SetError(err)
return false

View File

@ -1,7 +1,7 @@
package upload
import (
"code.hoteas.com/golang/hotime"
. "../../common"
"errors"
"io"
"mime/multipart"
@ -50,7 +50,7 @@ func (this *Upload) UpFile(Request *http.Request, fieldName, savefilepath, saveP
}
}
}
filename := time.Unix(int64(t), 0).Format("2006-01-02-15-22-25") + hotime.ObjToStr(hotime.Rand(6))
filename := time.Unix(int64(t), 0).Format("2006-01-02-15-22-25") + ObjToStr(Rand(6))
filePath = path + "/" + filename + this.Path
} else {
filePath = savePath

View File

@ -2,8 +2,11 @@ package main
import (
"../../hotime"
"../../hotime/cache"
"../../hotime/common"
"database/sql"
"fmt"
//"go.hoteas.com/hotime/cache"
"golang.org/x/net/websocket"
"time"
@ -24,7 +27,7 @@ func main() {
//手动模式,
appIns.SetConfig("example/config/config.json")
//redis缓存接入
//ca:=hotime.CacheIns(&hotime.CacheRedis{Host:appIns.Config.GetString("redisHost"),Pwd:appIns.Config.GetString("redisPwd"),Time:appIns.Config.GetCeilInt64("cacheLongTime")})
//ca:=cache.CacheIns(&cache.CacheRedis{Host:appIns.Config.GetString("redisHost"),Pwd:appIns.Config.GetString("redisPwd"),Time:appIns.Config.GetCeilInt64("cacheLongTime")})
//ca.Cache("xyzm","dasdas")
//ca.Cache("xyzn","dasdas")
//ca.Cache("xyzo","dasdas")
@ -33,12 +36,12 @@ func main() {
//mysql
//mysql.SetDB(&appIns)
//自动选择数据库
appIns.SetSession(hotime.CacheIns(&hotime.CacheMemory{}), hotime.CacheIns(&hotime.CacheDb{Db: &appIns.Db, Time: appIns.Config.GetInt64("cacheTime")}))
appIns.SetCache(hotime.CacheIns(&hotime.CacheMemory{}))
dbInterface := cache.HoTimeDBInterface(&appIns.Db)
appIns.SetSession(cache.CacheIns(&cache.CacheMemory{}), cache.CacheIns(&cache.CacheDb{Db: dbInterface, Time: appIns.Config.GetInt64("cacheTime")}))
//appIns.SetCache(cache.CacheIns(&cache.CacheMemory{}))
//快捷模式
appIns.SetDefault(func(err ...*hotime.Error) (*sql.DB, *sql.DB) {
appIns.SetDefault(func(err ...*common.Error) (*sql.DB, *sql.DB) {
query := appIns.Config.GetString("dbUser") + ":" + appIns.Config.GetString("dbPwd") +
"@tcp(" + appIns.Config.GetString("dbHost") + ":" + appIns.Config.GetString("dbPort") + ")/" + appIns.Config.GetString("dbName") + "?charset=utf8"
DB, e := sql.Open("mysql", query)
@ -59,7 +62,7 @@ func main() {
//
// return true
//})
hotime.LogError("dasdasdasdasdas")
//hotime.LogError("dasdasdasdasdas")
this.Display(5, "dsadas")
},
"websocket": func(this *hotime.Context) {

View File

@ -1,12 +1,17 @@
package hotime
import (
. "./cache"
. "./common"
)
//session对象
type SessionIns struct {
ShortCache CacheIns
LongCache CacheIns
SessionId string
Map
contextBase
ContextBase
}
func (this *SessionIns) set() {

13
type.go
View File

@ -6,16 +6,3 @@ type Proj map[string]Ctr
type Router map[string]Proj
type MethodRouter map[string]Method //直接字符串关联函数
type Method func(this *Context)
type CacheIns interface {
//set(key string, value interface{}, time int64)
//get(key string) interface{}
//delete(key string)
Cache(key string, data ...interface{}) *Obj
}
//单条缓存数据
type cacheData struct {
time int64
data interface{}
}

4
var.go
View File

@ -1,5 +1,9 @@
package hotime
import (
. "./common"
)
var IsRun = false //当前状态
var App = map[string]*Application{} //整个项目