robertkrimen / otto

A JavaScript interpreter in Go (golang)
http://godoc.org/github.com/robertkrimen/otto
MIT License
8.01k stars 584 forks source link

Freezing GO struct to consume by javascript modules #517

Open stockiNail opened 6 months ago

stockiNail commented 6 months ago

I'm addressing a use case where we need to pass to javascript module GO structs, to consume in read-only mode.

Otto is enabling in my app a pluggable approach where whoever can develop small pieces of code which will be triggered by event or by whatever else cause. The javascript plugin should consume data which are passed to it by functions, leverage on Otto implementation, but it shouldn't be able to change the struct, therefore it should only read the data.

I have tried to invoke Object.freeze against the GO structs (passed as argument or passed by Otto.toValue) but it doesn't work. It seems that the GO structs passed to javascript are not 100% javascript object and some javascript Object functions don't work against them. I have tried also to define writable and configurable flags (and extensible on the objects) on every single property (by defineProperty and using the descriptor) but it doesn't work.

Going a bit in deep in Otto source code, I see the following:

https://github.com/robertkrimen/otto/blob/b755419e33b794116f0dead00ac3cbe883462e0f/runtime.go#L666-L670

which probably could address this use case when implemented.

I know that a possible solution could be to clone the structs before passing them to javascript but this is very resource consuming and I would avoid it.

Maybe there is a trick that I haven't discoreved yet... ;)