steve landiss
steve landiss

Reputation: 1913

How do I force golang to link a file into my binary?

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?

Upvotes: 1

Views: 1211

Answers (1)

Alex Netkachov
Alex Netkachov

Reputation: 13522

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.

Upvotes: 4

Related Questions