How to Embed JavaScript in Go (goja)

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"));`)