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

This commit is contained in:
2020-02-20 14:20:56 +08:00
parent 9070bd2fe7
commit 0f29b3304e
23 changed files with 255 additions and 144 deletions
+59 -8
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)
}
}