How to properly load assets in Golang+Gopherjs?

91 views
Skip to first unread message

Omar Mustardo

unread,
Nov 29, 2016, 10:13:33 AM11/29/16
to golang-nuts
I've been learning how to do opengl/webgl graphics in Golang using https://github.com/goxjs/
It has conditional compilation so it can be compiled and run on either desktop as usual, or with gopherjs for web.

Most recently, I've made a spinning cube demo: https://omustardo.github.io/textured-cube/index.html

It worked out nicely, but gave me a bit of trouble when it came to loading the texture file. In order to maintain the desktop+web support, I had to add conditional compilation and deal with each case separately. The solution uses standard file reading for desktop and a http.Get request for web. I hard-coded my workspace base directory for desktop, and used the relative "assets/image.png" for web. Relevant code is in the link above in the assetloader folder. 

The issues that I've found with this approach are:
* I'm unable to run `gopherjs build` and load the demo locally because http.Get doesn't load local files. I can still use `gopherjs serve` so it isn't too bad.
* Hardcoding the base directory won't work well for collaboration / sharing.

I don't think there's a way to get around conditional compilation without embedding static asset files in the binary, which I'd rather avoid.
For the desktop version, I've considered using filepath.Join(os.Getenv("GOPATH"), "path/to/demo/basedir") rather than hardcoding the base directory, but then it depends on people having GOPATH set, and having only a single path (as opposed to multiple semicolon delimited ones). I also thought about somehow making symlinks to the assets directory, but that seems worse.
I don't have any better ideas for the web version, but I also haven't done much web development so perhaps someone knows a better way to get local assets in javascript than http.Get?

Thanks,
Omar
Reply all
Reply to author
Forward
0 new messages