Modifying the static file before Shelf handler returns it

101 views
Skip to first unread message

David Notik

unread,
Jan 19, 2016, 4:18:25 PM1/19/16
to Dart Server-side and Cloud Development
Hi! I'm trying to replace a string in my index.html (which is my SPA) with another string.


Shelf serves my index.html with the shelf_static lib:

final shelf.Handler staticHandler = shelf_static.createStaticHandler(
 config
['server']['directory'],
 defaultDocument
: 'index.html',
 serveFilesOutsidePath
: true);

...

static serveApp(App app, shelf.Request request, [String path]) {
 
return app.staticHandler(
     
new shelf.Request('GET', Uri.parse(app.serverPath + '/')));
}

Where/how might you recommend I modify the returned index.html? Read the file in as string, replace, then return it back? So then don't use shelf_static?

--D

Natalie Weizenbaum

unread,
Jan 19, 2016, 6:30:27 PM1/19/16
to David Notik, Dart Server-side and Cloud Development
You probably don't want to entirely avoid using shelf_static, since it has a bunch of nice caching logic that would be a pain to re-implement. I'd suggest you write a simple piece of middleware that detects responses to GET /index.html, reads in the response body, does the search-and-replace, and then uses Response.change() to return an updated response.

--
You received this message because you are subscribed to the Google Groups "Dart Server-side and Cloud Development" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cloud+un...@dartlang.org.
Visit this group at https://groups.google.com/a/dartlang.org/group/cloud/.

Anders Holmgren

unread,
Jan 19, 2016, 8:55:14 PM1/19/16
to Natalie Weizenbaum, David Notik, Dart Server-side and Cloud Development
I suspect that most use cases for variable substitution are cases where the response may change per request (e.g. per user) and shouldn't be cached. For such caches a template engine like mustache is likely a better fit

David Notik

unread,
Jan 19, 2016, 10:14:03 PM1/19/16
to Anders Holmgren, Natalie Weizenbaum, Dart Server-side and Cloud Development
Makes sense to me. Natalie would you concur?

Natalie Weizenbaum

unread,
Jan 20, 2016, 3:08:01 PM1/20/16
to David Notik, Anders Holmgren, Dart Server-side and Cloud Development
Sure. A clever template engine handler may even be able to cache based on a combination of template age and variable identity.

David Notik

unread,
Jan 20, 2016, 3:25:17 PM1/20/16
to Natalie Weizenbaum, Anders Holmgren, Dart Server-side and Cloud Development
Sure! It'd be a tiny improvement given my little change to the file contents. For now, injecting my user data into the file gave me a little server-side magic and substantially improved the load times for my Polymer SPA. (I was waiting until hasTriedLoadingUser, which was round-trip, before.) Woot!
--
Reply all
Reply to author
Forward
0 new messages