Search code examples
kongkong-plugin

Accessing datastore from Golang plugin


When writing plugins in Lua there is the kong.db module available to access the Kong's underlying database.

I assume that it also should be possible to communicate with the DB from within plugins written in Go. Or am I wrong here?

If it's possible what would be the way to grab connection details needed for a DB driver?

I'm running Kong in a Docker container and passing all relevant configs through environment variables, e.g

ENV KONG_PG_HOST=host
ENV KONG_PG_USER=user
ENV KONG_PG_DATABASE=kong
ENV KONG_PG_PORT=5432

Calling os.Getenv("KONG_PG_HOST") from within the plugin returns nothing though.


Solution

  • So, as mentioned in the comment @david-chandler linked one of the goals of go-pdk is to facilitate the usage of any library from the Go ecosystem. Everything is clear, no questions here.

    What I was not able to grasp is how to pass over database connection details (like host, user, password, etc.) - defined in my case in the Docker file of Kong - to whatever Go database driver.

    Diving a bit into Kong's source code revealed that whatever is specified under pluginserver_XXX_start_cmd configuration property is executed using the exec command.

    Knowing that I decided just to pass all the config I need as the command arguments, that is to say my Docker file would like something like that:

    FROM kong
    ...
    ENV KONG_PG_HOST=...
    ENV KONG_PG_USER=...
    ...
    ENV KONG_PLUGINSERVER_NAMES=my-plugin
    ENV KONG_PLUGINSERVER_MY_PLUGIN_START_CMD="/usr/local/bin/my-plugin $KONG_PG_HOST $KONG_PG_USER
    ...
    

    and from Go code these arguments are accessible through os.Args