SoFunction
Updated on 2025-03-03

An implementation example of calling JS code (otto) in Go

otto is a JavaScript interpreter implemented in Go language, and its project address is:/robertkrimen/otto

Otto implements most of the features of ECMAScript 5.1. You can use Otto to execute JavaScript code, and even define and call functions, manipulate objects, etc. But please note that Otto currently only supports ECMAScript 5.1 and does not support ECMAScript 6 or higher features.

If I have a file now, the contents are:

var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

function encodeInp(input) {
    var output = "";
    var chr1, chr2, chr3 = "";
    var enc1, enc2, enc3, enc4 = "";
    var i = 0;
    do {
        chr1 = (i++);
        chr2 = (i++);
        chr3 = (i++);
        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;
        if (isNaN(chr2)) {
            enc3 = enc4 = 64
        } else if (isNaN(chr3)) {
            enc4 = 64
        }
        output = output + (enc1) + (enc2) + (enc3) + (enc4);
        chr1 = chr2 = chr3 = "";
        enc1 = enc2 = enc3 = enc4 = ""
    } while (i < );
    return output
}

There is a function in this file for encryption (actually a base64), and when we write a crawler or something, we need to run this code and get the returned value.

Then we can write this in Go:

package main

import (
	"fmt"
	"/robertkrimen/otto"
	"io/ioutil"
)

func main() {
	filePath := "Path to your JS file"
	//Read the file content first	bytes, err := (filePath)
	if err != nil {
		panic(err)
	}

	vm := ()
	
	_, err = (string(bytes))
	if err!=nil {
		panic(err)
	}
	
	data := "You need to pass parameters to JS functions"
	//encodeInp is the function name of the JS function	value, err := ("encodeInp", nil, data) 
	if err != nil {
		panic(err)
	}
	(())
}

Then if you will use this code frequently in the future, you can also encapsulate it in a small way.

func JsParser(filePath string, functionName string, args... interface{}) (result string) {
	//Read in file	bytes, err := (filePath)
	if err!=nil {
		panic(err)
	}

	vm := ()
	_, err = (string(bytes))
	if err!=nil {
		panic(err)
	}
	value, err := (functionName, nil, args...)
	if err != nil {
		panic(err)
	}

	return ()
}

In fact, otto has many interesting functions, you can go to the otto github project to see.

This is the end of this article about the implementation example of calling JS code (otto) in Go. For more related content on calling JS code, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!