External Readers

pkl-go provides APIs that aid in implementing External Readers. In this mode of execution, the program built with pkl-go runs as a child process of the Pkl evaluator, rather than a parent process. The pkl.ExternalReaderClient type provides a set of tools for building external readers.

Much like implementing Custom Readers, external readers are implemented by providing one or more instances of the pkl.ResourceReader and pkl.ModuleReader interfaces.

Example

This simple reader implementation reads the specified environment variable:

main.go
package main

import (
	"log"
	"net/url"
	"os"

	"github.com/apple/pkl-go/pkl"
)

func main() {
	client, err := pkl.NewExternalReaderClient(pkl.WithExternalClientResourceReader(myReader{}))
	if err != nil {
		log.Fatalln(err)
	}
	if err := client.Run(); err != nil {
		log.Fatalln(err)
	}
}

type myReader struct{}

var _ pkl.ResourceReader = &myReader{}

func (r myReader) Scheme() string {
	return "env2"
}

func (r myReader) HasHierarchicalUris() bool {
	return false
}

func (r myReader) IsGlobbable() bool {
	return false
}

func (r myReader) ListElements(baseURI url.URL) ([]pkl.PathElement, error) {
	return nil, nil
}

func (r myReader) Read(uri url.URL) ([]byte, error) {
	return []byte(os.Getenv(uri.Opaque)), nil
}