optimise www redirect check

minor init.js optimisation
avoid gzip for empty obj in alerts endpoint
This commit is contained in:
Azareal 2020-03-06 13:07:28 +10:00
parent 8f21d34964
commit d2828471cd
4 changed files with 58 additions and 48 deletions

View File

@ -840,6 +840,7 @@ func (r *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}
// Redirect www. and local IP requests to the right place
if strings.HasPrefix(shost, "www.") || c.Site.LocalHost {
if shost == "www." + c.Site.Host || (c.Site.LocalHost && shost != c.Site.Host && isLocalHost(shost)) {
// TODO: Abstract the redirect logic?
w.Header().Set("Connection", "close")
@ -858,6 +859,7 @@ func (r *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, dest, http.StatusMovedPermanently)
return
}
}
// Deflect malformed requests
if len(req.URL.Path) == 0 || req.URL.Path[0] != '/' || (!c.Config.LooseHost && shost != c.Site.Host) {

View File

@ -1,15 +1,15 @@
'use strict';
var me = {};
var phraseBox = {};
if(tmplInits===undefined) var tmplInits = {};
var tmplPhrases = []; // [key] array of phrases indexed by order of use
var hooks = { // Shorten this list by binding the hooks just in time?
"pre_iffe": [],
"pre_init": [],
"start_init": [],
"almost_end_init": [],
"end_init": [],
var me={};
var phraseBox={};
if(tmplInits===undefined) var tmplInits={};
var tmplPhrases=[]; // [key] array of phrases indexed by order of use
var hooks={ // Shorten this list by binding the hooks just in time?
"pre_iffe":[],
"pre_init":[],
"start_init":[],
"almost_end_init":[],
"end_init":[],
"after_phrases":[],
"after_add_alert":[],
"after_update_alert_list":[],
@ -18,7 +18,7 @@ var hooks = { // Shorten this list by binding the hooks just in time?
"edit_item_pre_bind":[],
"analytics_loaded":[],
};
var ranInitHooks = {}
var ranInitHooks={}
function runHook(name, ...args) {
if(!(name in hooks)) {
@ -33,9 +33,9 @@ function runHook(name, ...args) {
return ret;
}
function addHook(name, callback) {
function addHook(name, h) {
if(hooks[name]===undefined) hooks[name] = [];
hooks[name].push(callback);
hooks[name].push(h);
}
// InitHooks are slightly special, as if they are run, then any adds after the initial run will run immediately, this is to deal with the async nature of script loads
@ -45,22 +45,22 @@ function runInitHook(name, ...args) {
return ret;
}
function addInitHook(name, callback) {
addHook(name, callback);
if(name in ranInitHooks) callback();
function addInitHook(name, h) {
addHook(name, h);
if(name in ranInitHooks) h();
}
// Temporary hack for templates
function len(item) {
function len(it) {
return item.length;
}
function asyncGetScript(source) {
return new Promise((resolve, reject) => {
function asyncGetScript(src) {
return new Promise((resolve,reject) => {
let script = document.createElement('script');
script.async = true;
const onloadHandler = (e, isAbort) => {
const onloadHandler = (e,isAbort) => {
if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
script.onload = null;
script.onreadystatechange = null;
@ -75,17 +75,17 @@ function asyncGetScript(source) {
};
script.onload = onloadHandler;
script.onreadystatechange = onloadHandler;
script.src = source;
script.src = src;
const prior = document.getElementsByTagName('script')[0];
prior.parentNode.insertBefore(script, prior);
});
}
function notifyOnScript(source) {
source = "/s/"+source;
function notifyOnScript(src) {
src = "/s/"+src;
return new Promise((resolve, reject) => {
let ss = source.replace("/s/","");
let ss = src.replace("/s/","");
try {
let ssp = ss.charAt(0).toUpperCase() + ss.slice(1)
console.log("ssp:",ssp)
@ -95,8 +95,8 @@ function notifyOnScript(source) {
}
} catch(e) {}
console.log("source:",source)
let script = document.querySelectorAll('[src^="'+source+'"]')[0];
console.log("src:",src)
let script = document.querySelectorAll('[src^="'+src+'"]')[0];
console.log("script:",script);
if(script===undefined) {
reject("no script found");
@ -117,7 +117,7 @@ function notifyOnScript(source) {
});
}
function notifyOnScriptW(name, complete, success) {
function notifyOnScriptW(name,complete,success) {
notifyOnScript(name)
.then(() => {
console.log("Loaded " +name+".js");
@ -132,7 +132,7 @@ function notifyOnScriptW(name, complete, success) {
}
// TODO: Send data at load time so we don't have to rely on a fallback template here
function loadScript(name, callback,fail) {
function loadScript(name,callback,fail) {
let fname = name;
let value = "; " + document.cookie;
let parts = value.split("; current_theme=");
@ -142,18 +142,18 @@ function loadScript(name, callback,fail) {
let iurl = "/s/"+name+".js"
asyncGetScript(url)
.then(callback)
.catch((e) => {
.catch(e => {
console.log("Unable to get script '"+url+"'");
if(fname!=name) {
asyncGetScript(iurl)
.then(callback)
.catch((e) => {
console.log("Unable to get script '"+iurl+"'");
console.log("e: ", e);
console.log("e:", e);
console.trace();
});
}
console.log("e: ", e);
console.log("e:", e);
console.trace();
fail(e);
});
@ -166,8 +166,8 @@ function loadTmpl(name,callback) {
}
*/
function DoNothingButPassBack(item) {
return item;
function DoNothingButPassBack(it) {
return it;
}
function RelativeTime(date) {
@ -243,8 +243,8 @@ function fetchPhrases(plist) {
if(loggedIn) {
fetch("/api/me/")
.then((resp) => resp.json())
.then((data) => {
.then(resp => resp.json())
.then(data => {
console.log("loaded me endpoint data");
console.log("data:",data);
me = data;
@ -254,4 +254,4 @@ function fetchPhrases(plist) {
me = {User:{ID:0,S:""},Site:{"MaxRequestSize":0}};
runInitHook("pre_init");
}
})();
})()

View File

@ -84,7 +84,7 @@ func main() {
vcpy := route.Vars
route.Vars = []string{"h"}
route.Vars = append(route.Vars, vcpy...)
}/* else if route.Name != "common.RouteWebsockets" {
} /* else if route.Name != "common.RouteWebsockets" {
//out += "\n\t\t\tsa := time.Now()"
//out += "\n\t\t\tcn := uutils.Nanotime()"
}*/
@ -167,8 +167,8 @@ func main() {
/*if !route.Action && !route.NoHead && !group.NoHead {
out += "\n\t\t\t\t\tco.RouteViewCounter.Bump2(" + strconv.Itoa(allRouteMap[route.Name]) + ", h.StartedAt)"
} else {*/
//out += "\n\t\t\t\t\tco.RouteViewCounter.Bump(" + strconv.Itoa(allRouteMap[route.Name]) + ")"
out += "\n\t\t\t\t\tco.RouteViewCounter.Bump3(" + strconv.Itoa(allRouteMap[route.Name]) + ", cn)"
//out += "\n\t\t\t\t\tco.RouteViewCounter.Bump(" + strconv.Itoa(allRouteMap[route.Name]) + ")"
out += "\n\t\t\t\t\tco.RouteViewCounter.Bump3(" + strconv.Itoa(allRouteMap[route.Name]) + ", cn)"
//}
}
@ -193,8 +193,8 @@ func main() {
/*if !defaultRoute.Action && !defaultRoute.NoHead && !group.NoHead {
out += "\n\t\t\t\t\tco.RouteViewCounter.Bump2(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ", h.StartedAt)"
} else {*/
//out += "\n\t\t\t\t\tco.RouteViewCounter.Bump(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ")"
out += "\n\t\t\tco.RouteViewCounter.Bump3(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ", cn)"
//out += "\n\t\t\t\t\tco.RouteViewCounter.Bump(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ")"
out += "\n\t\t\tco.RouteViewCounter.Bump3(" + strconv.Itoa(allRouteMap[defaultRoute.Name]) + ", cn)"
//}
}
out += `
@ -559,6 +559,7 @@ func (r *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
}
// Redirect www. and local IP requests to the right place
if strings.HasPrefix(shost, "www.") || c.Site.LocalHost {
if shost == "www." + c.Site.Host || (c.Site.LocalHost && shost != c.Site.Host && isLocalHost(shost)) {
// TODO: Abstract the redirect logic?
w.Header().Set("Connection", "close")
@ -577,6 +578,7 @@ func (r *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
http.Redirect(w, req, dest, http.StatusMovedPermanently)
return
}
}
// Deflect malformed requests
if len(req.URL.Path) == 0 || req.URL.Path[0] != '/' || (!c.Config.LooseHost && shost != c.Site.Host) {

View File

@ -131,12 +131,23 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
topCreatedAt = uCreatedAt
}
}
err = rows.Err()
if err != nil {
if err = rows.Err(); err != nil {
return c.InternalErrorJS(err, w, r)
}
}
if count == 0 || len(alerts) == 0 || (rCreatedAt != 0 && rCreatedAt >= topCreatedAt && count == rCount) {
gzw, ok := w.(c.GzipResponseWriter)
if ok {
w = gzw.ResponseWriter
h := w.Header()
h.Del("Content-Type")
h.Del("Content-Encoding")
}
_, _ = io.WriteString(w, `{}`)
return nil
}
// Might not want to error here, if the account was deleted properly, we might want to figure out how we should handle deletions in general
list, err := c.Users.BulkGetMap(actors)
if err != nil {
@ -144,11 +155,6 @@ func routeAPI(w http.ResponseWriter, r *http.Request, user c.User) c.RouteError
return c.InternalErrorJS(err, w, r)
}
if count == 0 || len(alerts) == 0 || (rCreatedAt != 0 && rCreatedAt >= topCreatedAt && count == rCount) {
_, _ = io.WriteString(w, `{}`)
return nil
}
var ok bool
var sb strings.Builder
sb.Grow(c.AlertsGrowHint + (len(alerts) * c.AlertsGrowHint2))