Embed JavaScript in Go using the Goja library to run scripts and call Go functions directly within your application.
Embed JavaScript in Go by creating a Goja VM instance, running your script, and calling Go functions via vm.Set. This allows you to execute JS code and interact with Go data structures directly.
import "github.com/dop251/goja"
vm := goja.New()
vm.Set("greet", func(name string) string {
return "Hello, " + name
})
vm.RunString(`console.log(greet("World"));`)
Goja lets you run JavaScript code inside a Go program without needing an external browser or Node.js. It works like a mini JavaScript engine built directly into your Go application. You can use it to run scripts, calculate values, or even let JavaScript call your Go functions.