It is possible, but it’s hard to do.
You can’t access files using WebAssembly. Instead, you need the user to drop a folder inside the webpage and use the File and Directory Entries API to get the files and their contents.
But the real problem is passing the files from JS to WASM and vice-versa. You’ll also need to replace in the compiler source code all the calls to the Go standard library that would access files to calls to JS functions. Those function need to access the WASM memory directly. You will need to modify the compiler quite a bit.
To download the binary, you can create a Blob
, use URL.createObjectURL()
to get an URL to that blob, create an <a>
element with .download = true
and .href = <the blob URL>
, and then .click()
it.
The performance might be worse than running the Go compiler directly, but other than that it should work just fine.
I recently found out that Go compiles down to WebAssembly. Cool!
As per this Go doc, the Go toolchain itself is written in Go.
This made me think, can the Go compiler run in the browser? Can I make a website which given a file path through an upload button (though, without uploading anything), can compile a Go project and return the executable as a “download”?
The end result I’m looking for is an executable file saved to disk, not for the Go code to run in a browser, but I don’t need the exact scenario above to be followed as long as that is the final result.
If this is possible, what are the limitations, if any?
Additional resources I have looked at:
- A compiler from Go to WASM on GitHub
- Someone working on a game where entered Go code runs in the browser
EDIT: I have started work on this, based on a similar project. The repo can be found here: https://github.com/TR-SLimey/IBGC
Thanks for the answer! Would this be any easier if the source code was on a server instead, or a Git repo? I imagine that would spare me the JS->WASM file transfers since the WASM part could just fetch the source?
Yes. I mean, if instead of dragging a file over from the hard drive to compile, you provide it a Git repo URL of the code you want compiled. Then the compiler can access that code directly from the server almost like a file, instead of having to transfer the file between JS and WASM. Unless what I just said doesn’t make sense; which wouldn’t surprise me as I’m new to WASM.
Unless you somehow embedded that file inside the WASM code, you would still need to transfer the file from JS to WASM.
I see. How annoying. In any case, thank you, I’ll accept your answer now 🙂