scriptinggoembedding

Embed a scripting language inside Go


Is it possible to embed a language inside Go? I need it to create plugins inside my application.


Solution

  • At the first, I'll explain cgo. Go provides API to export values into C language.

    http://golang.org/cmd/cgo/

    For example, you can export string as char* like below.

    package main
    
    /*
    #include <stdio.h>
    static void myputs(char* s) {
        puts(s);
    }
    */
    import "C"
    
    func main() {
        s := "hello world"
        C.myputs(C.CString(s))
    }
    

    So you need to write functions to access C library. But there are some packages to use script languages. See:

    https://github.com/mattn/go-mruby

    https://github.com/mattn/go-v8

    Or if you don't want to use C language. You can use native go language like otto

    https://github.com/robertkrimen/otto

    https://github.com/mattn/anko