3
头图

Go Eval library

Golang of eval() function third-party implementations.

background

As we all know, Golang is a static language. As an old comrade who switched from a dynamic language (don’t guess I’m phper), I’m used to using eval() to think about Go dynamically executing code.

How golang use eval() function, php , javascript comes with this feature. Golang officially does not provide related libraries.

In the rich Go third-party ecosystem, there is really no relevant library found. I saw someone made a demo and posted it on the blog. I came to use it to change, and made a library, I hope that the majority of gopher is satisfied.

installation

$ go get github.com/PaulXu-cn/goeval

Features

This goeval library, pass in the golang code string, and then execute the eval() function, you can get the string code output to stdout .

Examples of use:

package main

import (
    "fmt"
    "github.com/PaulXu-cn/goeval"
)

func main() {
    if re, err := goeval.Eval(
        "",
        "fmt.Print(\"Hello World! itjsz.com\")",
        "fmt"); nil == err {
        fmt.Print(string(re))
    } else {
        fmt.Print(err.Error())
    }
}

Output:

Hello World! itjsz.com

Here we introduce the goeval package, call its Eval function, the first parameter is the structure definition code (because there is no useful custom structure in the code, so pass empty here), the second string is the code to be executed , The third and subsequent strings are imported packages.

Implementation rules

  1. Construct the entire string of running code according to the incoming string
  2. Formatting code is mainly to delete unused packages, so there can be more packages of import
  3. Create a random directory under the tmp
  4. main.go file in the newly created directory
  5. Write formatted code
  6. Run go run main.go and collect stdout
  7. Delete the created folder and main.go
  8. Return stdout

reference


小白要生发
1k 声望1.2k 粉丝

GoPHPer工程师