1

How internally play.golang.org compiles and run the go code?

I have a function as string. I need to check the syntax and run the code inside golang main function.

1
  • 5
    For playground internals, see: blog.golang.org/playground. Otherwise, if you want to run Go code, compile and run the Go code. Commented May 23, 2017 at 15:33

2 Answers 2

4

The code is sent to a server to be compiled and executed then the output is sent back to the client (the browser).

There is an article on how it works : https://blog.golang.org/playground

Sign up to request clarification or add additional context in comments.

Comments

1

Go code is a bit hard to run dynamically. You can "check" the syntax with the parser package, although using those packages under go can be a bit tricky. To actually run it, you would likely need to:

  1. Save the function to a temporary directory, possibly generating a main to invoke it.
  2. exec the go compiler to generate an executable
  3. Run the compiled binary, possibly piping stdin and stdout to the parent process.
  4. Communicate with it over stdin/stdout until it exits

This is obviously a big runaround and quite a pain.

If go is not strictly required there are multiple scripting languages with go implementations. If you supply javascript or lua or whatever code, you can run that dynamically.

3 Comments

Incidentally, for an example of how to do this, check out the mockgen portion of Gomock: github.com/golang/mock/tree/master/mockgen. That's exactly how that library generates mocks, it creates a new go program using templates, then compiles and executes it to generate the actual mock code.
Which one is faster in execution? Whether scripting language or create, compile and run the golang?
Without details of your use case, it is hard to say. The compiling option is going to have a longer time to start up, but may run faster. If it matters, benchmark it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.