增加跨域配置,以及增加配置说明

This commit is contained in:
hoteas 2020-02-20 14:20:56 +08:00
parent 9070bd2fe7
commit 0f29b3304e
23 changed files with 255 additions and 144 deletions

View File

@ -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)
}
}

74
cache/cache_redis.go vendored
View File

@ -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

View File

@ -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)
}

View File

@ -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#"
const HEAD_SESSION_ADD = "session#"

View File

@ -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)

View File

@ -4,7 +4,7 @@ import "time"
type contextBase struct {
Error
tag int64
tag int64
}
//唯一标志

View File

@ -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 {

View File

@ -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()

View File

@ -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

View File

@ -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
}

View File

@ -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": "如果使用自动数据库配置请设置此项手动配置数据库不需要目前支持mysqlsqlite",
"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服务时配置默认服务ip127.0.0.1",
"redisPort": "需要使用redis服务时配置默认服务端口6379",
"redisPwd": "需要使用redis服务时配置默认服务密码123456",
"sessionName": "设置session的cookie名默认HOTIME",
"tlsCert": "https证书",
"tlsKey": "https密钥",
"tlsPort": "web服务https端口0为不启用https服务",
"tpt": "静态文件目录默认为程序目录下tpt目录"
}

View File

@ -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") +

23
func.go
View File

@ -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)
//}

4
map.go
View File

@ -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 {

4
obj.go
View File

@ -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 {

View File

@ -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<len(s);i++{
res=append(res,s.GetMap(i))
s := ObjToSlice(obj, e...)
res := []Map{}
for i := 0; i < len(s); i++ {
res = append(res, s.GetMap(i))
}
return res
}
@ -142,24 +141,25 @@ func ObjToFloat64(obj interface{}, e ...*Error) float64 {
return v
}
//向上取整
func ObjToCeilInt64(obj interface{}, e ...*Error)int64{
f:=ObjToCeilFloat64(obj,e...)
return ObjToInt64(math.Ceil(f))
func ObjToCeilInt64(obj interface{}, e ...*Error) int64 {
f := ObjToCeilFloat64(obj, e...)
return ObjToInt64(math.Ceil(f))
}
//向上取整
func ObjToCeilFloat64(obj interface{}, e ...*Error)float64{
f:=ObjToFloat64(obj,e...)
return math.Ceil(f)
func ObjToCeilFloat64(obj interface{}, e ...*Error) float64 {
f := ObjToFloat64(obj, e...)
return math.Ceil(f)
}
//向上取整
func ObjToCeilInt(obj interface{}, e ...*Error)int{
f:=ObjToCeilFloat64(obj,e...)
return ObjToInt(f)
func ObjToCeilInt(obj interface{}, e ...*Error) int {
f := ObjToCeilFloat64(obj, e...)
return ObjToInt(f)
}
@ -208,7 +208,7 @@ func ObjToInt64(obj interface{}, e ...*Error) int64 {
}
func ObjToInt(obj interface{}, e ...*Error) int {
v:=ObjToInt64(obj,e...)
v := ObjToInt64(obj, e...)
return int(v)
}

View File

@ -12,10 +12,10 @@ type SessionIns struct {
func (this *SessionIns) set() {
if this.ShortCache != nil {
this.ShortCache.Cache(HEAD_SESSION_ADD + this.SessionId, this.Map)
this.ShortCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)
}
if this.LongCache != nil {
this.LongCache.Cache(HEAD_SESSION_ADD + this.SessionId, this.Map)
this.LongCache.Cache(HEAD_SESSION_ADD+this.SessionId, this.Map)
}
}

View File

@ -33,12 +33,14 @@ func (this Slice) GetCeilInt64(key int, err ...*Error) int64 {
return v
}
//获取向上取整Int
func (this Slice) GetCeilInt(key int, err ...*Error) int {
v := ObjToCeilInt((this)[key], err...)
return v
}
//获取向上取整float64
func (this Slice) GetCeilFloat64(key int, err ...*Error) float64 {
v := ObjToCeilFloat64((this)[key], err...)

View File

@ -2,8 +2,8 @@ package db
import (
"code.hoteas.com/hoteas/hotime"
"code.hoteas.com/hoteas/hotime/dri/mysql"
"code.hoteas.com/hoteas/hotime/dri/sqlite"
"code.hoteas.com/hoteas/hotime/tools/mysql"
"code.hoteas.com/hoteas/hotime/tools/sqlite"
"strings"
)

View File

@ -4,7 +4,7 @@ package hotime
type Ctr map[string]Method
type Proj map[string]Ctr
type Router map[string]Proj
type MethodRouter map[string]Method//直接字符串关联函数
type MethodRouter map[string]Method //直接字符串关联函数
type Method func(this *Context)
type CacheIns interface {
@ -14,10 +14,8 @@ type CacheIns interface {
Cache(key string, data ...interface{}) *Obj
}
//单条缓存数据
type cacheData struct {
time int64
data interface{}
}

68
var.go
View File

@ -1,32 +1,70 @@
package hotime
var IsRun = false //当前状态
var App = map[string]*Application{} //整个项目
var IsRun = false //当前状态
var App = map[string]*Application{} //整个项目
//var Db = HoTimeDB{} //数据库实例
var Config = Map{
"tpt": "tpt",
"debug": 1, //debug 0关闭1开启
"logLevel": LOG_NIL,
"defFile": []string{"index.html", "index.htm"},
"dbHost": "127.0.0.1",
//"dbHost":"localhost",
"dbName": "test",
"dbUser": "root",
"dbPwd": "root",
"dbPort": "3306",
"dbCached":0,//0不开启缓存
"port": "0",
"dbCached": 0, //0不开启缓存
"cacheShortTime": 60 * 60 * 2,
"cacheLongTime": 60 * 60 * 24 * 30,
"sessionName": "HOTIME",
"error": Map{
"1":"系统错误",
"error": Map{
"1": "内部系统异常",
"2": "访问权限异常",
"3": "请求参数异常",
"4": "数据处理异常",
"5": "数据结果异常",
},
"debug":1,//debug 0关闭1开启
"modeRouterStrict":false,//路由严格模式/a/b/c
"tlsPort":"0",
"tlsKey":"",
"tlsCert":"",
"tpt": "tpt",
"defFile": []string{"index.html", "index.htm"},
"crossDomain": "", //是否开启跨域
"modeRouterStrict": false, //路由严格模式/a/b/c
"port": "0",
"sessionName": "HOTIME",
"tlsPort": "0",
"tlsKey": "",
"tlsCert": "",
}
var ConfigNote = Map{
"logLevel": "日志等级0打印1关闭2记录到文件",
"debug": "是否开启debug模式0关闭其他开启debug模式下日志展示更全", //debug 0关闭1开启
"dbHost": "数据库ip地址默认127.0.0.1",
"dbName": "数据库名称sqlite为文件路径比如a/x.db",
"dbUser": "数据库用户名",
"dbPwd": "数据库密码",
"dbPort": "数据库端口",
"dbType": "如果使用自动数据库配置请设置此项手动配置数据库不需要目前支持mysqlsqlite",
"dbCached": "是否开启数据库缓存0为关闭其他开启", //0不开启缓存
"redisHost": "需要使用redis服务时配置默认服务ip127.0.0.1",
"redisPort": "需要使用redis服务时配置默认服务端口6379",
"redisPwd": "需要使用redis服务时配置默认服务密码123456",
"cacheShortTime": "两级缓存短缓存存储时间60 * 60 * 2一般为内存缓存",
"cacheLongTime": "两级缓存长缓存存储时间60 * 60 * 24 * 30一般为数据库或者redis缓存",
"error": Map{
"1": "内部系统异常,在环境配置,文件访问权限等基础运行环境条件不足造成严重错误时使用",
"2": "访问权限异常,没有登录或者登录异常等时候使用",
"3": "请求参数异常request参数不满足要求比如参数不足参数类型错误参数不满足要求等时候使用",
"4": "数据处理异常,数据库操作或者三方请求返回的结果非正常结果,比如数据库突然中断等时候使用",
"5": "数据结果异常一般用于无法给出response要求的格式要求下使用比如response需要的是string格式但你只能提供int数据时",
"注释": "web服务内置错误提示自定义异常建议10开始",
},
"tpt": "静态文件目录默认为程序目录下tpt目录",
"defFile": "默认访问文件默认访问index.html或者index.htm文件",
"crossDomain": "跨域设置,空字符串为不开启,*为开启所有网站允许跨域http://www.baidu.com为指定域允许跨域", //是否开启跨域
"modeRouterStrict": "路由严格模式false,为大小写忽略必须匹配true必须大小写匹配", //路由严格模式/a/b/c
"sessionName": "设置session的cookie名默认HOTIME",
"port": "web服务开启Http端口0为不启用http服务",
"tlsPort": "web服务https端口0为不启用https服务",
"tlsKey": "https密钥",
"tlsCert": "https证书",
}