1

I want to create a module library where a files can be added and will be part of my binary.

For example, in my package main I have:

type InitFunc func(params DriverParams) (Driver, error)

func Register(name string, f InitFunc) {
}

Then I would like someone to add a file in the modules directory that calls Register().

Subsequently my main package will call all the functions that have registered themselves.

This way, my main package has no prior knowledge of the modules that will be added.

How do I accomplish this in golang?

steve landiss
  • 1,833
  • 3
  • 19
  • 30
  • When you say 'binary' are you talking about another Go package? Not to be confused with something like a dll produced by gcc. – evanmcdonnal Jul 29 '15 at 21:06
  • The current stable version of Go (1.4) doesn't have this; Go 1.5's beta has some stuff. I don't know enough for an answer (or have time right now to look it up), but `buildmode` is one of the switches involved; see http://stackoverflow.com/questions/30896892/using-go-1-5-buildmode-c-archive-with-net-http-server-linked-from-c for example – twotwotwo Jul 29 '15 at 21:09
  • When I say 'binary' I just mean that when I do a go build or go run, it does not automatically include the file in the modules directory because no one in my main package is referencing it. Therefore, the file in the modules directory never gets to call the function "Register". I want it to be able to call Register with out me having to reference that file from my main package. – steve landiss Jul 29 '15 at 21:14
  • 3
    While there will be some support for building shared libraries in go1.5, the framework for "plugins" isn't there yet. You might be able to work something together via `-buildmode=c-shared` and cgo wrappers, but I wouldn't recommend it. – JimB Jul 29 '15 at 21:17

1 Answers1

4

In short - you cannot. Go links everything statically and does some optimizations so the module you installing may not even be compiled if you do not reference it explicitly from main. Such limitation makes people suffer and they do this - the plugins are just normal Go applications communicating with the main app via RPC.

It may sound weird (when one part of your app talks to another via TCP stack), but if you think about a bit more then it actually gives you quite strong confidence that plugin will do no harm to the application. For example, when the plugin crashes, the rest of the application, most likely, will survive.

Alex Netkachov
  • 13,172
  • 6
  • 53
  • 85