Goja Golang JavaScript Runtime Features and Examples

Author

Reads 383

Street market in Anjuna, Goa with vibrant clothing stalls and nearby beach cafe.
Credit: pexels.com, Street market in Anjuna, Goa with vibrant clothing stalls and nearby beach cafe.

Goja is a JavaScript runtime for Go, allowing developers to run JavaScript code within a Go program. It's a powerful tool for building web applications and APIs.

Goja provides a JavaScript engine that can be embedded in Go programs, enabling them to execute JavaScript code seamlessly. This allows developers to leverage the strengths of both languages.

Goja's JavaScript engine is based on the V8 engine, which is also used by Google Chrome. This means that Goja inherits the performance and reliability of V8.

Goja's API is designed to be easy to use and provides a simple way to interact with JavaScript code from Go.

If this caught your attention, see: S Golang

Goja Basics

Goja is a native implementation for running JavaScript in Go, making it a great option for projects that require JavaScript support.

Goja has full ECMAScript 5.1 support, which means it covers all the features of the language.

Goja also has unit tests for almost all ES5.1 features, making it easy to verify the language features quickly.

If you need to run JavaScript from your Go program, Goja is definitely worth considering.

Assigning and Returning

Woman Programming on a Notebook
Credit: pexels.com, Woman Programming on a Notebook

Assigning and Returning Values in Goja is a breeze, thanks to Go's reflection mechanism. This means you don't need to specify the type of the array when iterating through it.

Goja can infer the type of the array based on its content, which is a huge time-saver. This is especially useful when working with dynamic data.

You'll notice that when filtering values and returning the result, Goja converts the result back to an array of empty interfaces ([]interface{}). This is necessary to handle JavaScript's dynamic typing within Go's static type system.

Internally, Goja represents all integers as int64, so be prepared to perform type assertions to extract the integers if you need to work with the resulting values in Go.

For more insights, see: Golang Type

Structs and Methods

In Goja, structs are handled in a way that's easy to understand. The naming conventions on the struct are adhered to when accessing its fields and methods from JavaScript.

A Person struct with an exported Name field and an unexported age field is a good example of this. The GetName method is exported, which means it can be accessed from JavaScript.

Credit: youtube.com, This is your last video about Golang Structs!

The method GetAge is accessed as GetName in JavaScript, because Goja follows the naming conventions on the struct. This might seem counterintuitive at first, but it's a consistent approach.

To make the JavaScript naming convention of camel case translate to Go naming convention, Goja uses a FieldNameMapper. This allows for the Go method GetAge to be called as getAge in the JavaScript invocation.

Safe Get in 1.9.11

In Goja, version 1.9.11 introduced a new function called SafeGet, which is a game-changer for error handling.

SafeGet attempts to get the value associated with a key, and catches the panic that Goja creates if an error occurs.

This function is a must-know for developers working with Goja, as it helps prevent crashes and provides a more robust way to handle errors.

To use SafeGet, simply pass in the key as a parameter, and Goja will return the associated value or catch any errors that may occur.

Related reading: Golang Goja Async Await

Complete Example

Senior couple completes payment with waiter in stylish restaurant setting, showcasing hospitality service.
Credit: pexels.com, Senior couple completes payment with waiter in stylish restaurant setting, showcasing hospitality service.

To get started with Goja, it's helpful to understand the different deployments that have been tested. This demo was tested in the following deployments:

Goja's versions are identified by Git commit hashes, not traditional version numbers. This is something to keep in mind when working with the tool.

Go Packages for JS Execution

You can run JavaScript in Go using various packages, but one option is to use V8 bindings for Go.

There are a few packages available, including GitHub - behrsin/go-v8: V8 Bindings for Go, GitHub - augustoroman/v8: A Go API for the V8 javascript engine, and GitHub - rogchap/v8go: Execute JavaScript from Go.

If you need full language support, Goja is a native implementation that has Full ECMAScript 5.1 and has unit tests for almost all ES5.1 features.

Source Files

Goja source files are written in the Goja language and have a .goja extension.

The Goja compiler can compile Goja source files into bytecode.

From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio
Credit: pexels.com, From above crop faceless male developer in black hoodie writing software code on netbook while working in light studio

Goja source files typically start with a package declaration, specifying the name of the package and its location.

Each Goja source file can contain multiple functions, which are blocks of code that perform a specific task.

Goja functions can take arguments, which are values passed to the function when it's called.

Goja source files can also contain variables, which are values that can be used and modified within the file.

Goja variables can be declared with a specific type, such as int or string, or left untyped.

Curious to learn more? Check out: Create a Package in Golang

Error Handling

Error handling in Goja is a breeze, thanks to its standard Go error handling approach. This means you can easily manage runtime exceptions like division by zero.

The error value returned is of type *goja.Exception, which provides valuable information about the JavaScript exception that was raised and where it failed. This information can be logged to services like New Relic or DataDog for further analysis.

Goja offers the tools to inspect these errors, but in most cases, logging them is sufficient. You can also raise other types of exceptions, such as *goja.StackOverflowError, *goja.InterruptedError, and *goja.CompilerSyntaxError, which correspond to specific issues related to the interpreter.

Initialization

Credit: youtube.com, Online Golang Conf 2021 : Using goja as a scripting layer for go applications | Simon Aronsson

Initialization in Goja is straightforward. Goja does not provide a global variable, and it can be created in one line.

To get started, you'll need to initialize Goja. This can be done by calling the necessary function to create a new instance.

Goja can also handle base64 encoded strings passed from the JavaScript context to Go code.

Initialize

Initializing a program is a crucial step in getting started with a new project. Goja doesn't provide a global variable, so it must be created in one line.

To begin, you need to initialize Goja. This can be done by creating a global variable, which in Goja can be done in one line.

Goja can be initialized with a single line of code, making it a straightforward process.

Curious to learn more? Check out: Golang Line

Making Specialized Objects Available in JavaScript

To make your app scriptable, you need to expose parts of it to the script. For example, in Google Sheets, you have a SpreadsheetApp object that provides access to the spreadsheet.

Programming Code on Screen
Credit: pexels.com, Programming Code on Screen

You can create an object in Go and add it to the globals of the JavaScript Runtime. This allows you to make parts of your app available to the script.

A custom object can be created in Go and added to the globals of the JavaScript Runtime. This object can then be used by the script to interact with your app.

To make the custom object useful, you need to add methods to it that allow the users to register their "hooks". Hooks are pointers to functions inside the script.

The hooks are stored in a table and called when an event occurs. In the TriggerNewEmailEvent function, the Value object is converted to a function and called passing the Email object.

Goja can convert from a Go struct to a JavaScript object. This is useful for simple cases like passing values.

Additional reading: Golang Go

Go to JavaScript

Go to JavaScript is a breeze with goja. You can easily map values from Go to JavaScript and vice versa using the Value interface defined in goja.

Credit: youtube.com, Go for JS Devs | Ep. 0 | Why Learn Go in 2022?

The goja.Runtime has a function ToValue() that converts from native Go type to internal representation for the JavaScript VM. This function is used to convert values from Go to JavaScript, for example, vm.ToValue("a string value") converts from Go string.

You can also convert values from JavaScript to Go using the Value interface functions like value.ToBoolean() or value.ToString(). Sometimes, it's more convenient to export to a provided variable, in which case you can use value.ExportTo().

Calling a JavaScript function from Go is also straightforward. You can create a specialized object available in JavaScript by adding a method to the custom object that makes it possible for users to register their “hooks”. Hooks are pointers to functions inside the script, and you can keep them in a table and call them when an event occurs.

goja can convert from Go struct to JavaScript object, which is useful in simple cases such as passing values. For more closer integration, you will have to make a custom Object like that of the myemail object.

JavaScript Execution

Credit: youtube.com, Go (Golang) vs Node.js: Performance (Latency - Throughput - Saturation - Availability)

JavaScript Execution is a crucial aspect of the goja golang library. You can run JavaScript code from Go using the goja library, which provides a native implementation of the JavaScript engine.

The goja library has three packages available for running JavaScript: GitHub - behrsin/go-v8: V8 Bindings for Go, GitHub - augustoroman/v8: A Go API for the V8 javascript engine, and GitHub - rogchap/v8go: Execute JavaScript from Go. These packages provide different ways to execute JavaScript code from Go.

To run simple JavaScript code from Go, you can use the goja library. Let's try getting familiar with the goja library by running some JavaScript code. You can do this by using the goja.Runtime Get() function to get values from the global object.

Here are some examples of how to execute JavaScript code using the goja library:

  • goja.Runtime Get() function
  • vm.Get("myFunction")
  • ExportTo function
  • RunTime.ToValue() function

You can also use the JSRE (JavaScript Runtime Environment) to execute JavaScript code. The JSRE provides helper functions to load code from files, run code snippets, and bind native Go objects to JavaScript.

Evaluate JSRE Function

Close-up of a computer screen displaying colorful programming code with depth of field.
Credit: pexels.com, Close-up of a computer screen displaying colorful programming code with depth of field.

To evaluate JavaScript code, you can use the Evaluate function from the JSRE library. This function executes the code and pretty prints the result to the specified output stream.

The Evaluate function takes JavaScript code as input and returns the execution result. This is useful for running simple JavaScript code from Go, as shown in the example.

You can pass the JavaScript code to be executed as a string to the Evaluate function. The function will then execute the code and print the result.

The Evaluate function is a powerful tool for executing JavaScript code from Go. It allows you to run JavaScript code directly from your Go program.

Func (*JSRE) Exec

In order to execute JavaScript code, you can use the Exec function from the JSRE. This function loads and executes the contents of a JavaScript file.

The file path can be an absolute path or a relative path, which is resolved relative to the JSRE's asset path.

Here are the details of the Exec function: file: The path to the JavaScript file to execute. Can be an absolute path or relative to assetPath.

Callbacks and Interrupts

Colorful lines of code on a computer screen showcasing programming and technology focus.
Credit: pexels.com, Colorful lines of code on a computer screen showcasing programming and technology focus.

MakeCallback is a function that turns a given function into a function callable by JavaScript, which is a useful tool for interacting with the JavaScript world.

In Goja, you can use MakeCallback to create a function that can be called from JavaScript, which opens up a lot of possibilities for integration and interaction between the two languages.

To stop the current JavaScript evaluation, you can use the Interrupt function, which is available on the *JSRE type.

Here's an interesting read: Golang Use Cases

Callback Added in 1.9.11

Callbacks and Interrupts are powerful tools in programming, and one of the most significant updates in this area is the addition of the MakeCallback function in version 1.9.11.

MakeCallback turns the given function into a function that's callable by JS, allowing for more flexibility in how callbacks are used.

This update is a game-changer for developers who work with callbacks and interrupts, enabling them to write more efficient and effective code.

In version 1.9.11, the MakeCallback function was added, making it easier to work with callbacks and interrupts.

With MakeCallback, developers can now create functions that can be called by JavaScript, opening up new possibilities for callback-based programming.

Interrupt Added in 1.10.14

Credit: youtube.com, Interrupts and Callbacks

The Interrupt feature was added in version 1.10.14 of the JSRE.

This new feature allows developers to stop the current JavaScript evaluation with a single function call, providing more control over the execution flow.

The Interrupt function is straightforward: it simply stops the current evaluation, without waiting for any ongoing operations to complete.

In contrast, the Stop function, which is available in earlier versions, terminates the event loop and gives any remaining timers a chance to expire before shutting down.

With Interrupt, developers can now more easily pause and resume their JavaScript code, making it easier to work with complex asynchronous operations.

Frequently Asked Questions

Is Netflix using Golang?

Yes, Netflix is utilizing Go (Golang) for building internal tools. They leverage Go for high-performance systems, such as Chaos Monkey, which tests the resilience of their infrastructure.

Should I say Go or Golang?

When referring to the language, use "Go" to avoid confusion with the website name. Simply saying "Go" is the recommended choice for clarity and consistency.

Is Google still using Golang?

Yes, Google still uses Go (also known as Golang) in production. It's a widely adopted language in many organizations and open-source projects.

Gilbert Deckow

Senior Writer

Gilbert Deckow is a seasoned writer with a knack for breaking down complex technical topics into engaging and accessible content. With a focus on the ever-evolving world of cloud computing, Gilbert has established himself as a go-to expert on Azure Storage Options and related topics. Gilbert's writing style is characterized by clarity, precision, and a dash of humor, making even the most intricate concepts feel approachable and enjoyable to read.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.