iedc-go/application.go

459 lines
11 KiB
Go
Raw Normal View History

2017-08-17 02:14:59 +00:00
package hotime
import (
"bytes"
"database/sql"
"encoding/json"
"io/ioutil"
"net/http"
2019-05-19 15:33:01 +00:00
"net/url"
2017-08-17 02:14:59 +00:00
"os"
"path/filepath"
"strconv"
"strings"
)
type Application struct {
2018-11-14 02:31:08 +00:00
MethodRouter
2017-08-17 02:14:59 +00:00
Router
2017-08-23 07:35:49 +00:00
contextBase
2017-08-17 02:14:59 +00:00
Port string //端口号
2019-11-10 10:00:45 +00:00
TLSPort string //ssl访问端口号
2017-08-22 08:24:55 +00:00
connectListener []func(this *Context) bool //所有的访问监听,true按原计划继续使用false表示有监听器处理
2017-08-17 02:14:59 +00:00
connectDbFunc func(err ...*Error) *sql.DB
configPath string
Config Map
Db HoTimeDB
2017-10-27 04:28:47 +00:00
Server *http.Server
2017-08-17 02:14:59 +00:00
CacheIns
sessionLong CacheIns
sessionShort CacheIns
2017-10-27 04:28:47 +00:00
http.Handler
}
func (this *Application) ServeHTTP(w http.ResponseWriter, req *http.Request) {
this.handler(w, req)
2017-08-17 02:14:59 +00:00
}
//启动实例
func (this *Application) Run(router Router) {
2020-02-21 13:44:53 +00:00
//如果没有设置配置自动生成配置
if this.configPath == "" || len(this.Config) == 0 {
this.SetConfig()
}
//防止手动设置缓存误伤
if this.CacheIns == nil {
this.SetCache(CacheIns(&CacheMemory{}))
}
//防止手动设置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")}))
}
}
2018-04-03 17:54:27 +00:00
2017-08-17 02:14:59 +00:00
this.Router = router
2018-11-14 02:31:08 +00:00
//重新设置MethodRouter//直达路由
2019-05-19 15:33:01 +00:00
this.MethodRouter = MethodRouter{}
modeRouterStrict := true
if this.Config.Get("modeRouterStrict").(bool) == false {
modeRouterStrict = false
2018-11-15 03:44:50 +00:00
}
2019-05-19 15:33:01 +00:00
if router != nil {
for pk, pv := range router {
if !modeRouterStrict {
pk = strings.ToLower(pk)
2018-11-15 03:44:50 +00:00
}
2019-05-19 15:33:01 +00:00
if pv != nil {
for ck, cv := range pv {
if !modeRouterStrict {
ck = strings.ToLower(ck)
2018-11-15 03:44:50 +00:00
}
2019-05-19 15:33:01 +00:00
if cv != nil {
for mk, mv := range cv {
if !modeRouterStrict {
mk = strings.ToLower(mk)
2018-11-14 02:31:08 +00:00
}
2019-05-19 15:33:01 +00:00
this.MethodRouter["/"+pk+"/"+ck+"/"+mk] = mv
2018-11-14 02:31:08 +00:00
}
2019-05-19 15:33:01 +00:00
}
2018-11-14 02:31:08 +00:00
}
}
}
}
2017-08-17 02:14:59 +00:00
//this.Port = port
this.Port = this.Config.GetString("port")
2019-05-27 05:46:03 +00:00
this.TLSPort = this.Config.GetString("tlsPort")
2017-08-17 02:14:59 +00:00
2019-05-19 15:33:01 +00:00
if this.connectDbFunc != nil && (this.Db.DB == nil || this.Db.DB.Ping() != nil) {
2017-08-17 02:14:59 +00:00
this.Db.SetConnect(this.connectDbFunc)
}
if this.CacheIns == nil {
this.CacheIns = CacheIns(&CacheMemory{Map: Map{}, Time: this.Config.GetInt64("cacheShortTime")})
}
2017-10-13 09:52:34 +00:00
//异常处理
defer func() {
if err := recover(); err != nil {
//this.SetError(errors.New(fmt.Sprint(err)), LOG_FMT)
logFmt(err, 2, LOG_ERROR)
2017-10-13 09:52:34 +00:00
this.Run(router)
}
}()
2017-10-27 04:28:47 +00:00
this.Server = &http.Server{}
if !IsRun {
IsRun = true
}
2019-05-27 05:46:03 +00:00
ch := make(chan int)
2019-11-10 10:00:45 +00:00
if ObjToCeilInt(this.Port) != 0 {
go func() {
2019-07-01 04:35:04 +00:00
2019-05-27 05:46:03 +00:00
App[this.Port] = this
this.Server.Handler = this
//启动服务
this.Server.Addr = ":" + this.Port
2019-11-10 10:00:45 +00:00
err := this.Server.ListenAndServe()
logFmt(err, 2)
2019-11-10 10:00:45 +00:00
ch <- 1
2019-05-27 05:46:03 +00:00
2019-11-10 10:00:45 +00:00
}()
2020-07-16 17:10:28 +00:00
}
if ObjToCeilInt(this.TLSPort) != 0 {
2019-07-01 04:35:04 +00:00
go func() {
2019-05-27 05:46:03 +00:00
2019-11-10 10:00:45 +00:00
App[this.TLSPort] = this
this.Server.Handler = this
//启动服务
this.Server.Addr = ":" + this.TLSPort
err := this.Server.ListenAndServeTLS(this.Config.GetString("tlsCert"), this.Config.GetString("tlsKey"))
logFmt(err, 2)
2019-11-10 10:00:45 +00:00
ch <- 2
2019-07-01 04:35:04 +00:00
}()
2020-07-16 17:10:28 +00:00
}
if ObjToCeilInt(this.Port) == 0 && ObjToCeilInt(this.TLSPort) == 0 {
logFmt("没有端口启用", 2, LOG_INFO)
2019-07-01 04:35:04 +00:00
return
}
2019-11-10 10:00:45 +00:00
value := <-ch
2017-08-17 02:14:59 +00:00
logFmt("启动服务失败 : "+ObjToStr(value), 2, LOG_ERROR)
2017-08-17 02:14:59 +00:00
}
//启动实例
func (this *Application) SetConnectDB(connect func(err ...*Error) *sql.DB) {
2019-05-27 17:01:13 +00:00
//this.Db.DBCached=false
//if this.Config.GetCeilInt("dbCached")!=0{
// this.Db.DBCached=true
//}
2017-08-17 02:14:59 +00:00
this.connectDbFunc = connect
2017-10-24 01:31:20 +00:00
this.Db.SetConnect(this.connectDbFunc)
2019-05-27 17:01:13 +00:00
2019-11-10 10:00:45 +00:00
this.Db.DBCached = false
if this.Config.GetCeilInt("dbCached") != 0 {
this.Db.DBCached = true
2019-05-27 17:01:13 +00:00
}
2019-11-10 10:00:45 +00:00
this.Db.Type = this.Config.GetString("dbType")
2017-08-17 02:14:59 +00:00
}
//设置配置文件路径全路径或者相对路径
func (this *Application) SetSession(short CacheIns, Long CacheIns) {
this.sessionLong = Long
this.sessionShort = short
}
//默认配置缓存和session实现
func (this *Application) SetDefault(connect func(err ...*Error) *sql.DB) {
this.SetConfig()
2019-11-10 10:10:26 +00:00
if connect != nil {
this.connectDbFunc = connect
2017-10-24 01:31:20 +00:00
this.Db.SetConnect(this.connectDbFunc)
}
2017-08-17 02:14:59 +00:00
}
//设置配置文件路径全路径或者相对路径
func (this *Application) SetCache(cache CacheIns) {
this.CacheIns = cache
}
//设置配置文件路径全路径或者相对路径
func (this *Application) SetConfig(configPath ...string) {
if len(configPath) != 0 {
this.configPath = configPath[0]
}
if this.configPath == "" {
this.configPath = "config/config.json"
}
//加载配置文件
btes, err := ioutil.ReadFile(this.configPath)
this.Config = DeepCopyMap(Config).(Map)
if err == nil {
cmap := Map{}
//文件是否损坏
cmap.JsonToMap(string(btes), &this.Error)
for k, v := range cmap {
this.Config[k] = v //程序配置
Config[k] = v //系统配置
2017-08-17 02:14:59 +00:00
}
2019-11-10 10:00:45 +00:00
} else {
logFmt("配置文件不存在,或者配置出错,使用缺省默认配置", 2)
2019-05-27 05:46:03 +00:00
2017-08-17 02:14:59 +00:00
}
2019-09-03 03:55:05 +00:00
2017-08-17 02:14:59 +00:00
//文件如果损坏则不写入配置防止配置文件数据丢失
if this.Error.GetError() == nil {
var configByte bytes.Buffer
2017-08-17 02:14:59 +00:00
err = json.Indent(&configByte, []byte(this.Config.ToJsonString()), "", "\t")
2019-07-01 04:35:04 +00:00
//判断配置文件是否序列有变化有则修改配置,五则不变
//fmt.Println(len(btes))
if len(btes) != 0 && configByte.String() == string(btes) {
2019-07-01 04:35:04 +00:00
return
}
//写入配置说明
var configNoteByte bytes.Buffer
json.Indent(&configNoteByte, []byte(ConfigNote.ToJsonString()), "", "\t")
os.MkdirAll(filepath.Dir(this.configPath), os.ModeDir)
err = ioutil.WriteFile(this.configPath, configByte.Bytes(), os.ModeAppend)
2017-08-17 02:14:59 +00:00
if err != nil {
this.Error.SetError(err)
2017-08-17 02:14:59 +00:00
}
ioutil.WriteFile(filepath.Dir(this.configPath)+"/confignote.json", configNoteByte.Bytes(), os.ModeAppend)
2017-08-17 02:14:59 +00:00
}
}
//连接判断,返回true继续传输至控制层false则停止传输
2017-08-22 08:24:55 +00:00
func (this *Application) SetConnectListener(lis func(this *Context) bool) {
this.connectListener = append(this.connectListener, lis)
2017-08-17 02:14:59 +00:00
}
//网络错误
2018-04-03 17:54:27 +00:00
//func (this *Application) session(w http.ResponseWriter, req *http.Request) {
//
//}
2017-08-17 02:14:59 +00:00
2017-08-22 08:24:55 +00:00
//序列化链接
func (this *Application) urlSer(url string) (string, []string) {
q := strings.Index(url, "?")
2017-08-17 02:14:59 +00:00
if q == -1 {
2017-08-22 08:24:55 +00:00
q = len(url)
2017-08-17 02:14:59 +00:00
}
2017-08-22 08:24:55 +00:00
o := Substr(url, 0, q)
2017-08-17 02:14:59 +00:00
r := strings.SplitN(o, "/", -1)
var s = make([]string, 0)
for i := 0; i < len(r); i++ {
if !strings.EqualFold("", r[i]) {
s = append(s, r[i])
}
}
2017-08-22 08:24:55 +00:00
return o, s
}
//访问
2018-11-15 03:44:50 +00:00
2017-08-22 08:24:55 +00:00
func (this *Application) handler(w http.ResponseWriter, req *http.Request) {
2019-07-01 04:35:04 +00:00
_, s := this.urlSer(req.RequestURI)
2017-08-22 08:24:55 +00:00
//获取cookie
// 如果cookie存在直接将sessionId赋值为cookie.Value
// 如果cookie不存在就查找传入的参数中是否有token
// 如果token不存在就生成随机的sessionId
// 如果token存在就判断token是否在Session中有保存
// 如果有取出token并复制给cookie
// 没有保存就生成随机的session
2018-04-07 16:54:08 +00:00
cookie, err := req.Cookie(this.Config.GetString("sessionName"))
2017-08-22 08:24:55 +00:00
sessionId := Md5(strconv.Itoa(Rand(10)))
token := req.FormValue("token")
//isFirst:=false
if err != nil || (len(token) == 32 && cookie.Value != token) {
if len(token) == 32 {
sessionId = token
}
//else{
// isFirst=true;
//}
2018-04-07 16:54:08 +00:00
http.SetCookie(w, &http.Cookie{Name: this.Config.GetString("sessionName"), Value: sessionId, Path: "/"})
2017-08-22 08:24:55 +00:00
} else {
sessionId = cookie.Value
}
2017-08-17 02:14:59 +00:00
2019-05-19 15:33:01 +00:00
unescapeUrl, err := url.QueryUnescape(req.RequestURI)
if err != nil {
unescapeUrl = req.RequestURI
2018-11-06 14:57:53 +00:00
}
2017-08-22 08:24:55 +00:00
//访问实例
context := Context{SessionIns: SessionIns{SessionId: sessionId,
LongCache: this.sessionLong,
ShortCache: this.sessionShort,
},
CacheIns: this.CacheIns,
2018-11-06 14:57:53 +00:00
Resp: w, Req: req, Application: this, RouterString: s, Config: this.Config, Db: &this.Db, HandlerStr: unescapeUrl}
2017-10-11 09:45:22 +00:00
//header默认设置
header := w.Header()
2017-10-12 02:07:51 +00:00
header.Set("Content-Type", "text/html; charset=utf-8")
2018-11-14 16:10:41 +00:00
//url去掉参数并序列化
context.HandlerStr, context.RouterString = this.urlSer(context.HandlerStr)
//跨域设置
2020-02-21 13:44:53 +00:00
this.crossDomain(&context)
2020-02-20 07:06:39 +00:00
//是否展示日志
if this.Config.GetInt("connectLogShow") != 0 {
logFmt(Substr(context.Req.RemoteAddr, 0, strings.Index(context.Req.RemoteAddr, ":"))+" "+context.HandlerStr, 0, LOG_INFO)
2020-02-20 07:06:39 +00:00
}
2017-08-22 08:24:55 +00:00
//访问拦截true继续false暂停
2017-10-11 09:45:22 +00:00
connectListenerLen := len(this.connectListener)
if connectListenerLen != 0 {
2017-08-22 08:24:55 +00:00
for i := 0; i < connectListenerLen; i++ {
if !this.connectListener[i](&context) {
2017-10-12 02:07:51 +00:00
2017-08-22 08:24:55 +00:00
context.View()
return
}
}
}
2018-11-14 16:10:41 +00:00
2017-08-17 02:14:59 +00:00
//接口服务
2018-11-14 02:31:08 +00:00
//if len(s) == 3 {
// //如果满足规则则路由到对应控制器去
// if this.Router[s[0]] != nil && this.Router[s[0]][s[1]] != nil && this.Router[s[0]][s[1]][s[2]] != nil {
// //控制层
// this.Router[s[0]][s[1]][s[2]](&context)
// //header.Set("Content-Type", "text/html; charset=utf-8")
// context.View()
// return
// }
//
//}
2018-11-15 03:44:50 +00:00
//验证接口严格模式
2019-05-19 15:33:01 +00:00
modeRouterStrict := this.Config.Get("modeRouterStrict").(bool)
tempHandlerStr := context.HandlerStr
if !modeRouterStrict {
tempHandlerStr = strings.ToLower(tempHandlerStr)
2018-11-15 03:44:50 +00:00
}
2017-08-17 02:14:59 +00:00
2018-11-15 03:44:50 +00:00
//执行接口
2019-05-19 15:33:01 +00:00
if this.MethodRouter[tempHandlerStr] != nil {
this.MethodRouter[tempHandlerStr](&context)
context.View()
return
2017-08-17 02:14:59 +00:00
}
//url赋值
2019-07-01 04:35:04 +00:00
path := this.Config.GetString("tpt") + tempHandlerStr
2017-08-17 02:14:59 +00:00
//判断是否为默认
if path[len(path)-1] == '/' {
2017-10-27 04:28:47 +00:00
defFile := this.Config.GetSlice("defFile")
2017-08-17 02:14:59 +00:00
for i := 0; i < len(defFile); i++ {
2017-10-27 04:28:47 +00:00
temp := path + defFile.GetString(i)
2017-08-17 02:14:59 +00:00
_, err := os.Stat(temp)
if err == nil {
path = temp
break
}
}
if path[len(path)-1] == '/' {
w.WriteHeader(404)
return
}
}
if strings.Contains(path, "/.") {
w.WriteHeader(404)
return
}
2017-10-12 02:07:51 +00:00
//设置header
2019-05-19 15:33:01 +00:00
delete(header, "Content-Type")
if this.Config.GetInt("debug") != 1 {
2018-05-29 17:39:37 +00:00
header.Set("Cache-Control", "public")
}
2017-10-12 02:07:51 +00:00
2019-05-19 15:33:01 +00:00
if strings.Index(path, ".m3u8") != -1 {
header.Add("Content-Type", "audio/mpegurl")
}
2017-08-17 02:14:59 +00:00
//w.Write(data)
http.ServeFile(w, req, path)
}
2020-02-21 13:44:53 +00:00
func (this *Application) crossDomain(context *Context) {
//没有跨域设置
2020-02-21 13:44:53 +00:00
if context.Config.GetString("crossDomain") == "" {
return
}
2020-02-21 13:44:53 +00:00
header := context.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")
2020-02-21 13:44:53 +00:00
if context.Config.GetString("crossDomain") != "*" {
header.Set("Access-Control-Allow-Origin", this.Config.GetString("crossDomain"))
return
}
2020-02-21 13:44:53 +00:00
origin := context.Req.Header.Get("Origin")
if origin != "" {
header.Set("Access-Control-Allow-Origin", origin)
return
}
2020-02-21 13:44:53 +00:00
refer := context.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)
}
}