Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to dynamically load Go code?

Tags:

go

As the title says I want to dynamically load a Go package (or not) based on information only available at run time.

The objective is to allow the user to extend the program via custom packages that add new native script commands. Currently every time I add new commands or want to disallow some commands, I need to edit the program and recompile, whereas if I could make some kind of dll or the like then I could create a "import" script command to search for and load a named command library.

For the curious the program in question is custom command based scripting library that I use for all kinds of things.

I did some searching ahead of time, and the results don't look good, but I could not find a clear no.

like image 848
Milo Christiansen Avatar asked Aug 14 '13 17:08

Milo Christiansen


1 Answers

Go does not support dynamic libraries yet. Elias Naur has recently published some patches, but they have not been reviewed yet and it is unlikely that they will be included in Go 1.2. You can read the discussions on Google Groups:

  • https://groups.google.com/d/topic/golang-nuts/o0VTTqC8hOU/discussion
  • https://groups.google.com/d/topic/golang-nuts/P05BDjLcQ5k/discussion

As far as I know, that are the most recent discussions about that topic.

There is however another approach. You can start your plugins in separate processes and use the net/rpc package to communicate with your main app. This also allows you to dynamically start / stop / recompile separate plugins and it has the advantage that a bad plugin can not crash your program. Go excels at network communication, you just have to make good use of it.

I need to edit the program and recompile,

You can also consider writing a small script that watches for changes in the current directory (using fsnotify) and executes "go build" followed by a restart of your program. I use this approach on some of my web projects during local development and it works fine. I am not able to observe any compilation times and I am quite fast at switching and refreshing my browser window. My Python development cycle, where the interpreter has to be restarted and all modules have to be reimported on every change (and that might take a significant time in larger projects!), feels really clumsy in comparison to Go.

like image 159
tux21b Avatar answered Oct 15 '22 06:10

tux21b