I'm trying to store some data in my local MongoDB instance using Go compiled to WebAssembly. The problem is, I cannot even connect to it. The mondog instance doesn't react to connection from wasm module in any way. This problem arises only when connecting from wasm module. The same code when compiled in ordinary way works fine, as well as connection from mongo shell. The runned mongod instance has no password protection.
My OS is Windows 10 in case that matters.
I've tried to change mongod bind_ip parameter from localhost to the actual local adress of my machine and use different browsers (Chrome 75.0.3770.80, Opera 60.0.3255.109). Changing the timeout duration doesn't do the trick also.
func connectToMongo(URI string, timeout time.Duration) *mongo.Client {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI(URI))
if err != nil {
log.Fatal(err)
}
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err) // It fails here
}
return client
}
func main() {
client := connectToMongo("mongodb://localhost:27017", 20*time.Second)
}
<html>
<head>
<script type="text/javascript" src="./wasm_exec.js"></script>
<script>
const go = new Go();
WebAssembly.instantiateStreaming(fetch('main.wasm'),go.importObject).then( res=> {
go.run(res.instance)
})
</script>
</head>
</html>
I run mongod.exe without any parameters so it is binded to localhost.
I expected my code to connect to mongod instance, but actually I get the following error in browser console: "context deadline exceeded".
I'm still learning Go and a total newbie in JavaScript so I might be missing something very simple. Any help would be greatly appreciated.
You are trying to connect from WebAssembly to a local server, most likely using a protocol which isn't allowed from the browser WASM sandbox.
WebAssembly can't for instance open low-level network sockets out of the WASM sandbox, you're mainly constrained to the same things that you can do with JavaScript in terms of file, system and network access when you're running WASM in a browser.
It's worth reading up on the constraints that WebAssembly has around security and system access when used in a browser context as well as it's worth noting that it's not WebAssembly that's blocking your connection here, it's the browser that's running the WebAssembly.