### Install Extism Go PDK Source: https://github.com/extism/go-pdk/blob/main/README.md Use 'go get' to include the go-pdk library in your project. ```bash go get github.com/extism/go-pdk ``` -------------------------------- ### Call Extism Plugin with Configuration Source: https://github.com/extism/go-pdk/blob/main/README.md Example of calling an Extism plugin using the CLI, passing configuration key-value pairs. ```bash extism call plugin.wasm greet --config user=Benjamin # => Hello, Benjamin! ``` -------------------------------- ### Get and Set Plugin Configuration in Go Source: https://github.com/extism/go-pdk/blob/main/README.md Retrieves configuration values set by the host. Requires the 'user' key to be present in the config. ```go //go:wasmexport greet func greet() int32 { user, ok := pdk.GetConfig("user") if !ok { pdk.SetErrorString("This plug-in requires a 'user' key in the config") return 1 } greeting := `Hello, ` + user + `!` pdk.OutputString(greeting) return 0 } ``` -------------------------------- ### Build and Run Reactor Module Source: https://github.com/extism/go-pdk/blob/main/example/reactor/README.md Build the Go plugin as a WASI module and then call an exported function using extism. This example requires the reactor module to be included for WASI features like file access to work correctly. ```bash tinygo build -target wasi -o reactor.wasm ./tiny_main.go extism call ./reactor.wasm read_file --input "./test.txt" --allow-path . --wasi --log-level info # => Hello World! ``` -------------------------------- ### Implement WASI Reactor Module in Go (Older TinyGo) Source: https://github.com/extism/go-pdk/blob/main/README.md Implement a WASI reactor module in Go for older TinyGo versions (below 0.34.0). This example uses `//export` and imports `wasi-reactor` for runtime initialization. ```go package main import ( "os" "github.com/extism/go-pdk" _ "github.com/extism/go-pdk/wasi-reactor" ) //export read_file func read_file() { name := pdk.InputString() content, err := os.ReadFile(name) if err != nil { pdk.Log(pdk.LogError, err.Error()) return } pdk.Output(content) } func main() {} ``` -------------------------------- ### Call Extism Plugin with HTTP and Host Allowlist Source: https://github.com/extism/go-pdk/blob/main/README.md Example of calling an Extism plugin that makes HTTP requests. Requires WASI and a host allowlist for the domain. ```bash extism call plugin.wasm http_get --wasi --allow-host='*.typicode.com' # => { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": false } ``` -------------------------------- ### Call Extism Plugin with Logging and WASI Source: https://github.com/extism/go-pdk/blob/main/README.md Example of calling an Extism plugin with logging enabled via the CLI. Requires WASI and a log level. ```bash extism call plugin.wasm log_stuff --wasi --log-level=debug 2023/10/12 12:11:23 Calling function : log_stuff 2023/10/12 12:11:23 An info log! 2023/10/12 12:11:23 A debug log! 2023/10/12 12:11:23 A warn log! 2023/10/12 12:11:23 An error log! ``` -------------------------------- ### Fetch and Forward Response Memory Source: https://context7.com/extism/go-pdk/llms.txt Performs an HTTP GET request, retrieves the response body, and forwards it directly to the host using zero-copy memory output. Requires the `github.com/extism/go-pdk` import. ```go //go:wasmexport fetch_and_forward func fetchAndForward() int32 { req := pdk.NewHTTPRequest(pdk.MethodGet, "https://api.example.com/data") res := req.Send() pdk.OutputMemory(res.Memory()) // forward response body directly — zero copy return 0 } ``` -------------------------------- ### Execute HTTP Request and Get Response in Go Source: https://context7.com/extism/go-pdk/llms.txt Use `Send` to execute an HTTP request and receive a response. The response includes status, body, and headers. ```go res := req.Send() fmt.Println(res.Status()) // e.g. 200 fmt.Println(string(res.Body())) // response body bytes fmt.Println(res.Headers()) // map[string]string of response headers ``` -------------------------------- ### Make HTTP GET Request in Go Source: https://github.com/extism/go-pdk/blob/main/README.md Sends an HTTP GET request to a specified URL and outputs the response body. Allows setting custom headers. ```go //go:wasmexport http_get func httpGet() int32 { // create an HTTP Request (withuot relying on WASI), set headers as needed req := pdk.NewHTTPRequest(pdk.MethodGet, "https://jsonplaceholder.typicode.com/todos/1") req.SetHeader("some-name", "some-value") req.SetHeader("another", "again") // send the request, get response back (can check status on response via res.Status()) res := req.Send() pdk.OutputMemory(res.Memory()) return 0 } ``` -------------------------------- ### Run Without Reactor Module (Error Example) Source: https://github.com/extism/go-pdk/blob/main/example/reactor/README.md Calling a WASI function without including the reactor module results in an error, demonstrating the necessity of the reactor module for WASI compatibility. ```bash extism call ./c.wasm read_file --input "./test.txt" --allow-path . --wasi --log-level info # => 2024/01/18 20:48:48 open ./test.txt: errno 76 ``` -------------------------------- ### Increment and Get Plugin Variable in Go Source: https://github.com/extism/go-pdk/blob/main/README.md Increments an integer variable stored across function calls. Initializes 'count' to 0 if not set. ```go //go:wasmexport count func count() int32 { count := pdk.GetVarInt("count") count = count + 1 pdk.SetVarInt("count", count) pdk.OutputString(strconv.Itoa(count)) return 0 } ``` -------------------------------- ### Greet User with String Input/Output Source: https://context7.com/extism/go-pdk/llms.txt Reads a UTF-8 string from the host, concatenates it with a greeting, and returns the result as a string. Requires the `github.com/extism/go-pdk` import. ```go //go:wasmexport greet func greet() int32 { name := pdk.InputString() pdk.OutputString("Hello, " + name + "!") return 0 } // extism call plugin.wasm greet --input "Alice" --wasi // => Hello, Alice! ``` -------------------------------- ### Initialize WASI Reactor for Older TinyGo Versions (Go) Source: https://context7.com/extism/go-pdk/llms.txt For TinyGo versions prior to 0.34.0, import the `wasi-reactor` package (blank import) to ensure libc and the Go runtime are initialized before any exported function runs. TinyGo 0.34+ handles this automatically. ```go //go:build !std package main import ( "os" "github.com/extism/go-pdk" _ "github.com/extism/go-pdk/wasi-reactor" // ensures runtime init for TinyGo ≤ 0.33 ) //export read_file func readFile() { name := pdk.InputString() content, err := os.ReadFile(name) if err != nil { pdk.Log(pdk.LogError, err.Error()) return } pdk.Output(content) } func main() {} // TinyGo ≤ 0.33: // tinygo build -target wasip1 -o reactor.wasm ./main.go // // TinyGo ≥ 0.34 (no import needed): // tinygo build -target wasip1 -buildmode=c-shared -o reactor.wasm ./main.go // // extism call ./reactor.wasm read_file --input "./test.txt" --allow-path . --wasi // => Hello World! ``` -------------------------------- ### Echo Input Bytes Source: https://context7.com/extism/go-pdk/llms.txt Reads raw bytes from the host and echoes them back as output. Requires the `github.com/extism/go-pdk` import. ```go package main import "github.com/extism/go-pdk" //go:wasmexport echo func echo() int32 { data := pdk.Input() // read raw bytes from the host pdk.Output(data) // echo them straight back return 0 } ``` -------------------------------- ### Compile Standard Go Toolchain Plugin (Bash) Source: https://context7.com/extism/go-pdk/llms.txt Compile a plugin using the standard Go toolchain. This method is an alternative to TinyGo and produces a WebAssembly binary. ```bash GOOS="wasip1" GOARCH="wasm" go build -o plugin.wasm -buildmode=c-shared main.go # Invoke the _start export (standard toolchain only supports main/`_start`) extism call plugin.wasm _start --wasi --allow-host='api.example.com' ``` -------------------------------- ### Output Version String Source: https://context7.com/extism/go-pdk/llms.txt Writes a hardcoded version string to the host output. Requires the `github.com/extism/go-pdk` import. ```go //go:wasmexport version func version() int32 { pdk.OutputString("1.0.0") return 0 } // extism call plugin.wasm version --wasi // => 1.0.0 ``` -------------------------------- ### Test error handling with Extism CLI Source: https://github.com/extism/go-pdk/blob/main/README.md Demonstrates testing the 'greet' function with 'Benjamin' input to trigger the error, and with 'Zach' to show success. Also shows how to check the exit status code. ```bash extism call plugin.wasm greet --input="Benjamin" --wasi # => Error: Sorry, we don't greet Benjamins! # => returned non-zero exit code: 1 echo $? # print last status code # => 1 extism call plugin.wasm greet --input="Zach" --wasi # => Hello, Zach! echo $? # => 0 ``` -------------------------------- ### Generate Plugin Bindings with XTP CLI Source: https://github.com/extism/go-pdk/blob/main/README.md Use the `xtp` CLI to generate boilerplate plugin project code based on a schema file. This command prompts for the desired language for the bindings. ```bash xtp plugin init --schema-file ./example-schema.yaml 1. TypeScript > 2. Go 3. Rust 4. Python 5. C# 6. Zig 7. C++ 8. GitHub Template 9. Local Template ``` -------------------------------- ### pdk.Output(data []byte) Source: https://context7.com/extism/go-pdk/llms.txt Allocates a host memory block, copies `data` into it, and sets it as the plug-in output. ```APIDOC ## pdk.Output(data []byte) ### Description Writes raw bytes to the host output. ### Parameters - `data` ([]byte): The byte slice to write as output. ### Returns None ``` -------------------------------- ### Build and Call Reactor Module (Older TinyGo) Source: https://github.com/extism/go-pdk/blob/main/README.md Build a WASI reactor module using TinyGo and call it with the Extism CLI. This is for versions below 0.34.0 and assumes the `main` function is not the primary export. ```bash tinygo build -target wasip1 -o reactor.wasm ./tiny_main.go extism call ./reactor.wasm read_file --input "./test.txt" --allow-path . --wasi --log-level info # => Hello World! ``` -------------------------------- ### Export a greet function in Go Source: https://github.com/extism/go-pdk/blob/main/README.md Defines an exported 'greet' function that takes string input and returns a greeting. Requires the '//go:wasmexport' comment. Input is read using pdk.Input() and output is sent with pdk.OutputString(). Exports must return an i32 status code (0 for success). ```go package main import ( "github.com/extism/go-pdk" ) //go:wasmexport greet func greet() int32 { input := pdk.Input() greeting := `Hello, ` + string(input) + `!` pdk.OutputString(greeting) return 0 } ``` -------------------------------- ### pdk.InputString() string Source: https://context7.com/extism/go-pdk/llms.txt A convenience wrapper around `Input()` that returns the input as a Go string. ```APIDOC ## pdk.InputString() string ### Description Reads the host input as a UTF-8 string. ### Parameters None ### Returns - `string`: The input data from the host as a string. ``` -------------------------------- ### Build Reactor Module with TinyGo Source: https://github.com/extism/go-pdk/blob/main/README.md Compile a Go program as a shared library for WASI reactor modules using TinyGo. Use the `-buildmode=c-shared` flag to ensure proper initialization of libc and the Go runtime. ```bash cd example/reactor tinygo build -target wasip1 -buildmode=c-shared -o reactor.wasm ./tiny_main.go extism call ./reactor.wasm read_file --input "./test.txt" --allow-path . --wasi --log-level info # => Hello World! ``` -------------------------------- ### Read Host Configuration with pdk.GetConfig Source: https://context7.com/extism/go-pdk/llms.txt Retrieve configuration values provided by the host using `pdk.GetConfig`. It returns the string value and a boolean indicating if the key was present. If the key is not found, a default value can be used. ```go //go:wasmexport greet_configured func greetConfigured() int32 { lang, ok := pdk.GetConfig("language") if !ok { lang = "en" } switch lang { case "es": pdk.OutputString("Hola, " + pdk.InputString() + "!") default: pdk.OutputString("Hello, " + pdk.InputString() + "!") } return 0 } // extism call plugin.wasm greet_configured --input "Alice" --config language=es --wasi // => Hola, Alice! ``` -------------------------------- ### Load Extism Plugin with Host Functions Source: https://github.com/extism/go-pdk/blob/main/README.md Load an Extism plugin and provide host functions to it. The `functions` argument takes a list of host functions to be made available to the plugin. ```python manifest = {"wasm": [{"path": "/path/to/plugin.wasm"}]} plugin = Plugin(manifest, functions=[a_python_func], wasi=True) result = plugin.call('hello_from_python', b'').decode('utf-8') print(result) ``` -------------------------------- ### Compile TinyGo Reactor Plugin (Bash) Source: https://context7.com/extism/go-pdk/llms.txt Compile a standard reactor plugin using TinyGo. This command produces a WebAssembly binary suitable for use with Extism. ```bash # Standard reactor plug-in tinygo build -o plugin.wasm -target wasip1 -buildmode=c-shared main.go # Test with Extism CLI extism call plugin.wasm greet --input "Alice" --wasi # => Hello, Alice! ``` -------------------------------- ### Export greet function with error handling in Go Source: https://github.com/extism/go-pdk/blob/main/README.md Modifies the 'greet' function to return an error using pdk.SetError() if the input name is 'Benjamin'. Non-zero return codes indicate failure. ```go //go:wasmexport greet func greet() int32 { name := string(pdk.Input()) if name == "Benjamin" { pdk.SetError(errors.New("Sorry, we don't greet Benjamins!")) return 1 } greeting := `Hello, ` + name + `!` pdk.OutputString(greeting) return 0 } ``` -------------------------------- ### Log Messages with pdk.Log Source: https://context7.com/extism/go-pdk/llms.txt Send log messages to the host runtime at various levels (Trace, Debug, Info, Warn, Error) using `pdk.Log`. This function does not require WASI syscall permissions. ```go //go:wasmexport process func process() int32 { pdk.Log(pdk.LogInfo, "process started") pdk.Log(pdk.LogDebug, "reading input") input := pdk.Input() if len(input) == 0 { pdk.Log(pdk.LogWarn, "empty input received") pdk.SetErrorString("no input provided") return 1 } pdk.Log(pdk.LogInfo, "process complete") pdk.Output(input) return 0 } // extism call plugin.wasm process --input "hello" --wasi --log-level=debug // => 2024/01/01 00:00:00 process started // => 2024/01/01 00:00:00 reading input // => 2024/01/01 00:00:00 process complete ``` -------------------------------- ### Test Wasm plugin with Extism CLI Source: https://github.com/extism/go-pdk/blob/main/README.md Executes the compiled Wasm plugin using the Extism CLI, calling the 'greet' function with specific input. ```bash extism call plugin.wasm greet --input "Benjamin" --wasi ``` -------------------------------- ### Compile Go to Wasm with TinyGo Source: https://github.com/extism/go-pdk/blob/main/README.md Compiles the Go source file into a Wasm module using TinyGo, targeting WASI. ```bash tinygo build -o plugin.wasm -target wasip1 -buildmode=c-shared main.go ``` -------------------------------- ### Create HTTP Request with pdk.NewHTTPRequest Source: https://context7.com/extism/go-pdk/llms.txt Construct an outbound HTTP request using `pdk.NewHTTPRequest`. The host mediates all network calls, and this does not require WASI network access. Ensure the host policy allows the requested domain. ```go //go:wasmexport fetch_todo func fetchTodo() int32 { req := pdk.NewHTTPRequest(pdk.MethodGet, "https://jsonplaceholder.typicode.com/todos/1") req.SetHeader("Accept", "application/json") res := req.Send() if res.Status() != 200 { pdk.SetErrorString("unexpected status: " + strconv.Itoa(int(res.Status()))) return 1 } pdk.OutputMemory(res.Memory()) return 0 } // extism call plugin.wasm fetch_todo --wasi --allow-host='*.typicode.com' // => {"userId":1,"id":1,"title":"delectus aut autem","completed":false} ``` -------------------------------- ### Integrate Standard Go HTTP Client with Extism Source: https://context7.com/extism/go-pdk/llms.txt Use `pdkhttp.HTTPTransport` to make standard Go `net/http` calls work within an Extism plugin. Set it as `http.DefaultTransport` or pass it to an `http.Client`. ```go //go:build std package main import ( "fmt" "io" "net/http" "os" pdk "github.com/extism/go-pdk" pdkhttp "github.com/extism/go-pdk/http" ) func main() { // Route all standard http calls through the Extism host http.DefaultTransport = &pdkhttp.HTTPTransport{} resp, err := http.Get("https://jsonplaceholder.typicode.com/todos/1") if err != nil { pdk.SetError(err) os.Exit(1) } defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) pdk.OutputString(string(body)) } // GOOS=wasip1 GOARCH=wasm go build -o plugin.wasm -buildmode=c-shared main.go // extism call plugin.wasm _start --wasi --allow-host='*.typicode.com' // => {"userId":1,"id":1,"title":"delectus aut autem","completed":false} ``` -------------------------------- ### Allocate Host Memory for Strings in Go Source: https://context7.com/extism/go-pdk/llms.txt Use `AllocateString` to copy a string into host memory. Remember to call `mem.Free()` when done to prevent memory leaks. ```go //go:wasmexport store_and_retrieve func storeAndRetrieve() int32 { mem := pdk.AllocateString("temporary value") defer mem.Free() // read it back retrieved := string(mem.ReadBytes()) pdk.OutputString(retrieved) return 0 } ``` -------------------------------- ### Compile Go to Wasm with native Go toolchain Source: https://github.com/extism/go-pdk/blob/main/README.md Compiles the Go source file into a Wasm module using the native Go toolchain. ```bash GOOS="wasip1" GOARCH="wasm" go build -o plugin.wasm -buildmode=c-shared main.go ``` -------------------------------- ### Manage Integer Variables with pdk.GetVarInt / pdk.SetVarInt Source: https://context7.com/extism/go-pdk/llms.txt These typed helpers simplify storing and retrieving integer values by handling the binary encoding and decoding to/from byte slices. ```go //go:wasmexport count func count() int32 { n := pdk.GetVarInt("count") n++ pdk.SetVarInt("count", n) pdk.OutputString(strconv.Itoa(n)) return 0 } // First call: => 1 // Second call: => 2 ``` -------------------------------- ### WASI Reactor Initialization Source: https://context7.com/extism/go-pdk/llms.txt Initialize WASI for non-`main` exports using the `wasi-reactor` sub-module, particularly for TinyGo versions prior to 0.34.0. ```APIDOC ### `wasi-reactor` sub-module — Initialize WASI for non-`main` exports (TinyGo ≤ 0.33) For TinyGo versions prior to 0.34.0, import the `wasi-reactor` package (blank import) to ensure libc and the Go runtime are initialized before any exported function runs. TinyGo 0.34+ handles this automatically with `-buildmode=c-shared`. ```go //go:build !std package main import ( "os" "github.com/extism/go-pdk" _ "github.com/extism/go-pdk/wasi-reactor" // ensures runtime init for TinyGo ≤ 0.33 ) //export read_file func readFile() { name := pdk.InputString() content, err := os.ReadFile(name) if err != nil { pdk.Log(pdk.LogError, err.Error()) return } pdk.Output(content) } func main() {} // TinyGo ≤ 0.33: // tinygo build -target wasip1 -o reactor.wasm ./main.go // // TinyGo ≥ 0.34 (no import needed): // tinygo build -target wasip1 -buildmode=c-shared -o reactor.wasm ./main.go // // extism call ./reactor.wasm read_file --input "./test.txt" --allow-path . --wasi // => Hello World! ``` ``` -------------------------------- ### Log Memory Blocks with pdk.LogMemory Source: https://context7.com/extism/go-pdk/llms.txt Log the content of a pre-allocated `pdk.Memory` block using `pdk.LogMemory`. This avoids an extra allocation when the string data is already in host memory. ```go //go:wasmexport log_input func logInput() int32 { mem := pdk.AllocateBytes(pdk.Input()) defer mem.Free() pdk.LogMemory(pdk.LogDebug, mem) pdk.OutputMemory(mem) return 0 } ``` -------------------------------- ### pdk.OutputString(s string) Source: https://context7.com/extism/go-pdk/llms.txt A convenience wrapper around `Output()` for string values. ```APIDOC ## pdk.OutputString(s string) ### Description Writes a UTF-8 string to the host output. ### Parameters - `s` (string): The string to write as output. ### Returns None ``` -------------------------------- ### Transform Input Bytes Source: https://context7.com/extism/go-pdk/llms.txt Reads raw bytes from the host, transforms them to uppercase using `bytes.ToUpper`, and writes the result back to the host. Requires the `github.com/extism/go-pdk` import. ```go //go:wasmexport transform func transform() int32 { raw := pdk.Input() result := bytes.ToUpper(raw) // example transformation pdk.Output(result) return 0 } ``` -------------------------------- ### AllocateBytes / AllocateString Source: https://context7.com/extism/go-pdk/llms.txt Copies data into shared host memory and returns a `Memory` handle. Call `mem.Free()` when done to avoid leaks. ```APIDOC ## pdk.AllocateBytes(data []byte) pdk.Memory / pdk.AllocateString(s string) pdk.Memory ### Description Copies data into shared host memory and returns a `Memory` handle. Call `mem.Free()` when done to avoid leaks (unless the memory is being handed to the host as output or a variable value). ### Method (Function definitions) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** ([]byte) - The byte slice to allocate. - **s** (string) - The string to allocate. ### Request Example ```go //go:wasmexport store_and_retrieve func storeAndRetrieve() int32 { mem := pdk.AllocateString("temporary value") defer mem.Free() // read it back retrieved := string(mem.ReadBytes()) pdk.OutputString(retrieved) return 0 } ``` ### Response #### Success Response - **Memory** (pdk.Memory) - A handle to the allocated memory block. - **Offset()** (uint64) - Returns the memory offset. - **ReadBytes()** ([]byte) - Reads the memory block as bytes. - **Free()** - Frees the allocated memory. #### Response Example (See Request Example for usage) ``` -------------------------------- ### pdk.OutputJSON(v any) error Source: https://context7.com/extism/go-pdk/llms.txt Marshals `v` to JSON and sets the result as the plug-in output. ```APIDOC ## pdk.OutputJSON(v any) error ### Description Serializes a Go value as JSON and sends it to the host output. ### Parameters - `v` (any): The Go value to marshal into JSON. ### Returns - `error`: An error if the marshalling fails, otherwise nil. ``` -------------------------------- ### Allocate Typed Return Values with pdk Helpers (Go) Source: https://context7.com/extism/go-pdk/llms.txt Use pdk.ResultString to allocate a string in host memory and return its offset. This is suitable for returning values from an exported function back to the host. ```go //go:wasmexport get_version_offset func getVersionOffset() uint64 { return pdk.ResultString("1.2.3") // allocate "1.2.3" in host memory, return offset } ``` -------------------------------- ### JSON input and output for Extism exports in Go Source: https://github.com/extism/go-pdk/blob/main/README.md Defines Go structs for JSON parameters and results. Uses pdk.InputJSON() to unmarshal input and pdk.OutputJSON() to marshal output. Handles potential errors during JSON processing. ```go type Add struct { A int `json:"a"` B int `json:"b"` } type Sum struct { Sum int `json:"sum"` } //go:wasmexport add func add() int32 { params := Add{} // use json input helper, which automatically unmarshals the plugin input into your struct err := pdk.InputJSON(¶ms) if err != nil { pdk.SetError(err) return 1 } sum := Sum{Sum: params.A + params.B} // use json output helper, which automatically marshals your struct to the plugin output err := pdk.OutputJSON(sum) if err != nil { pdk.SetError(err) return 1 } return 0 } ``` -------------------------------- ### Decode Host Function Arguments with pdk Helpers (Go) Source: https://context7.com/extism/go-pdk/llms.txt Use pdk.ParamString to decode a string from a Wasm memory offset passed as an argument by the host. Ensure the offset is valid and points to a null-terminated string. ```go //go:wasmimport extism:host/user transform_string func transformString(inputOffset uint64) uint64 //go:wasmexport use_host_transform func useHostTransform() int32 { input := pdk.InputString() mem := pdk.AllocateString(input) defer mem.Free() resultOffset := transformString(mem.Offset()) result := pdk.ParamString(resultOffset) // decode the string at the returned offset pdk.OutputString(result) return 0 } ``` -------------------------------- ### pdk.Log Source: https://context7.com/extism/go-pdk/llms.txt Logs a message via the host runtime at the given level without requiring WASI syscall permissions. Available levels: `LogTrace`, `LogDebug`, `LogInfo`, `LogWarn`, `LogError`. ```APIDOC ## `pdk.Log(level pdk.LogLevel, s string)` — Log a message via the host runtime Sends a log message to the host at the given level without requiring WASI syscall permissions. Available levels: `LogTrace`, `LogDebug`, `LogInfo`, `LogWarn`, `LogError`. ### Example ```go //go:wasmexport process func process() int32 { pdk.Log(pdk.LogInfo, "process started") pdk.Log(pdk.LogDebug, "reading input") input := pdk.Input() if len(input) == 0 { pdk.Log(pdk.LogWarn, "empty input received") pdk.SetErrorString("no input provided") return 1 } pdk.Log(pdk.LogInfo, "process complete") pdk.Output(input) return 0 } ``` ``` -------------------------------- ### Ping with JSON Output Source: https://context7.com/extism/go-pdk/llms.txt Serializes a status result struct to JSON and sends it to the host. Handles potential errors during JSON marshaling. Requires the `github.com/extism/go-pdk` import. ```go type Result struct { Status string `json:"status"` Message string `json:"message"` } //go:wasmexport ping func ping() int32 { err := pdk.OutputJSON(Result{Status: "ok", Message: "pong"}) if err != nil { pdk.SetError(err) return 1 } return 0 } // extism call plugin.wasm ping --wasi // => {"status":"ok","message":"pong"} ``` -------------------------------- ### pdk.GetConfig Source: https://context7.com/extism/go-pdk/llms.txt Reads a host-provided configuration value. Returns the string value for `key` from the host-supplied config map, and a boolean indicating whether the key was present. ```APIDOC ## `pdk.GetConfig(key string) (string, bool)` — Read a host-provided configuration value Returns the string value for `key` from the host-supplied config map, and a boolean indicating whether the key was present. ### Example ```go //go:wasmexport greet_configured func greetConfigured() int32 { lang, ok := pdk.GetConfig("language") if !ok { lang = "en" } switch lang { case "es": pdk.OutputString("Hola, " + pdk.InputString() + "!") default: pdk.OutputString("Hello, " + pdk.InputString() + "!") } return 0 } ``` ``` -------------------------------- ### Manage Persistent Variables with pdk.GetVar / pdk.SetVar Source: https://context7.com/extism/go-pdk/llms.txt Use `pdk.GetVar` and `pdk.SetVar` to store and retrieve byte slices that persist across function calls for the lifetime of the plugin instance. `GetVar` returns `nil` if the key does not exist. ```go //go:wasmexport increment func increment() int32 { data := pdk.GetVar("hits") var hits int if data != nil { hits = int(binary.LittleEndian.Uint64(data)) } hits++ buf := make([]byte, 8) binary.LittleEndian.PutUint64(buf, uint64(hits)) pdk.SetVar("hits", buf) pdk.OutputString(strconv.Itoa(hits)) return 0 } ``` -------------------------------- ### AllocateJSON Source: https://context7.com/extism/go-pdk/llms.txt Marshals `v` to JSON and allocates the result in host memory, returning the `Memory` handle. ```APIDOC ## pdk.AllocateJSON(v any) (pdk.Memory, error) ### Description Marshals `v` to JSON and allocates the result in host memory, returning the `Memory` handle. ### Method (Function definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **v** (any) - The value to be marshalled to JSON and allocated. ### Request Example ```go type Report struct { Count int `json:"count"` Vowels string `json:"vowels"` } //go:wasmexport build_report func buildReport() int32 { r := Report{Count: 42, Vowels: "aeiou"} mem, err := pdk.AllocateJSON(r) if err != nil { pdk.SetError(err) return 1 } // use mem.Offset() to pass to host functions, then free when done defer mem.Free() pdk.OutputMemory(mem) return 0 } ``` ### Response #### Success Response - **Memory** (pdk.Memory) - A handle to the allocated JSON memory. - **error** (error) - An error if JSON marshalling fails. #### Response Example (See Request Example for usage) ``` -------------------------------- ### Add Numbers with JSON Input/Output Source: https://context7.com/extism/go-pdk/llms.txt Deserializes a JSON request containing two integers, calculates their sum, and serializes the result as JSON output. Handles potential errors during JSON processing. Requires the `github.com/extism/go-pdk` import. ```go type AddRequest struct { A int `json:"a"` B int `json:"b"` } type AddResponse struct { Sum int `json:"sum"` } //go:wasmexport add func add() int32 { var req AddRequest if err := pdk.InputJSON(&req); err != nil { pdk.SetError(err) return 1 } if err := pdk.OutputJSON(AddResponse{Sum: req.A + req.B}); err != nil { pdk.SetError(err) return 1 } return 0 } // extism call plugin.wasm add --input'{"a":20,"b":22}' --wasi // => {"sum":42} ``` -------------------------------- ### pdk.Input() []byte Source: https://context7.com/extism/go-pdk/llms.txt Reads raw bytes passed to the plug-in by the host for the current function call. ```APIDOC ## pdk.Input() []byte ### Description Reads raw bytes from the host. ### Parameters None ### Returns - `[]byte`: The raw input data from the host. ``` -------------------------------- ### Allocate Host Memory for JSON in Go Source: https://context7.com/extism/go-pdk/llms.txt Use `AllocateJSON` to marshal a Go value into JSON and allocate it in host memory. The returned `Memory` handle must be freed. ```go type Report struct { Count int `json:"count"` Vowels string `json:"vowels"` } //go:wasmexport build_report func buildReport() int32 { r := Report{Count: 42, Vowels: "aeiou"} mem, err := pdk.AllocateJSON(r) if err != nil { pdk.SetError(err) return 1 } // use mem.Offset() to pass to host functions, then free when done defer mem.Free() pdk.OutputMemory(mem) return 0 } ``` -------------------------------- ### Send Source: https://context7.com/extism/go-pdk/llms.txt Sends the request through the host and returns an HTTPResponse. ```APIDOC ## (*pdk.HTTPRequest).Send() pdk.HTTPResponse ### Description Sends the request through the host and returns an `HTTPResponse` containing the body, status code, and response headers. ### Method (Implicitly part of HTTPRequest object) ### Parameters None ### Request Example ```go res := req.Send() fmt.Println(res.Status()) // e.g. 200 fmt.Println(string(res.Body())) // response body bytes fmt.Println(res.Headers()) // map[string]string of response headers ``` ### Response #### Success Response - **HTTPResponse** (pdk.HTTPResponse) - An object containing the response body, status code, and headers. - **Status()** (int32) - Returns the HTTP status code. - **Body()** ([]byte) - Returns the response body as a byte slice. - **Headers()** (map[string]string) - Returns the response headers. #### Response Example ```go // Example usage within the Send() method description res := req.Send() fmt.Println(res.Status()) // e.g. 200 fmt.Println(string(res.Body())) // response body bytes fmt.Println(res.Headers()) // map[string]string of response headers ``` ``` -------------------------------- ### Test JSON export with Extism CLI Source: https://github.com/extism/go-pdk/blob/main/README.md Calls the 'add' Wasm function with JSON input and displays the JSON output. ```bash extism call plugin.wasm add --input='{"a": 20, "b": 21}' --wasi # => {"sum":41} ``` -------------------------------- ### pdk.InputJSON(v any) error Source: https://context7.com/extism/go-pdk/llms.txt Unmarshals the host-provided input bytes directly into `v` using `encoding/json`. ```APIDOC ## pdk.InputJSON(v any) error ### Description Deserializes JSON input from the host into a Go value. ### Parameters - `v` (any): A pointer to the Go value to unmarshal the JSON into. ### Returns - `error`: An error if the unmarshalling fails, otherwise nil. ``` -------------------------------- ### pdk.OutputMemory(mem pdk.Memory) Source: https://context7.com/extism/go-pdk/llms.txt Writes an already-allocated Memory block as output. This is a zero-copy output. ```APIDOC ## pdk.OutputMemory(mem pdk.Memory) ### Description Writes an already-allocated `Memory` block as output, enabling zero-copy. ### Parameters - `mem` (pdk.Memory): The memory block to write as output. ### Returns None ``` -------------------------------- ### JSONFrom Source: https://context7.com/extism/go-pdk/llms.txt Reads the host memory block at `offset` and unmarshals it into `v`. ```APIDOC ## pdk.JSONFrom(offset uint64, v any) error ### Description Reads the host memory block at `offset` and unmarshals it into `v`. ### Method (Function definition) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **offset** (uint64) - The offset of the memory block to read. - **v** (any) - The variable to unmarshal the JSON data into. ### Request Example ```go //go:wasmexport round_trip_json func roundTripJSON() int32 { type Payload struct{ Value string } orig := Payload{Value: "hello"} mem, _ := pdk.AllocateJSON(orig) var decoded Payload if err := pdk.JSONFrom(mem.Offset(), &decoded); err != nil { pdk.SetError(err) return 1 } pdk.OutputString(decoded.Value) // => hello return 0 } ``` ### Response #### Success Response - **error** (error) - Returns `nil` if unmarshalling is successful, otherwise returns an error. #### Response Example (See Request Example for usage) ``` -------------------------------- ### Call Imported Host Function in Go Source: https://github.com/extism/go-pdk/blob/main/README.md Invokes an imported host function, passing string data via memory and retrieving a response. ```go //go:wasmexport hello_from_python func helloFromPython() int32 { msg := "An argument to send to Python" mem := pdk.AllocateString(msg) defer mem.Free() ptr := aPythonFunc(mem.Offset()) rmem := pdk.FindMemory(ptr) response := string(rmem.ReadBytes()) pdk.OutputString(response) return 0 } ``` -------------------------------- ### pdk.GetVar / pdk.SetVar Source: https://context7.com/extism/go-pdk/llms.txt Persistent key-value store. Variables persist across function calls for the lifetime of the loaded plug-in instance. `GetVar` returns `nil` if the key does not exist. ```APIDOC ## `pdk.GetVar(key string) []byte` / `pdk.SetVar(key string, value []byte)` — Persistent key-value store Variables persist across function calls for the lifetime of the loaded plug-in instance. `GetVar` returns `nil` if the key does not exist. ### Example ```go //go:wasmexport increment func increment() int32 { data := pdk.GetVar("hits") var hits int if data != nil { hits = int(binary.LittleEndian.Uint64(data)) } hits++ buf := make([]byte, 8) binary.LittleEndian.PutUint64(buf, uint64(hits)) pdk.SetVar("hits", buf) pdk.OutputString(strconv.Itoa(hits)) return 0 } ``` ``` -------------------------------- ### Define a Python Host Function for Extism Source: https://github.com/extism/go-pdk/blob/main/README.md Define a Python host function that can be called from an Extism plugin. Ensure the function signature matches the expected input and output types. ```python from extism import host_fn, Plugin @host_fn() def a_python_func(input: str) -> str: # just printing this out to prove we're in Python land print("Hello from Python!") # let's just add "!" to the input string # but you could imagine here we could add some # applicaiton code like query or manipulate the database # or our application APIs return input + "!" ``` -------------------------------- ### pdk.NewHTTPRequest Source: https://context7.com/extism/go-pdk/llms.txt Creates an outbound HTTP request that will be executed by the host. Does not require WASI network access — the host mediates all network calls (subject to `--allow-host` policy). ```APIDOC ## `pdk.NewHTTPRequest(method pdk.HTTPMethod, url string) *pdk.HTTPRequest` — Create an outbound HTTP request Constructs an `HTTPRequest` that will be executed by the host. Does not require WASI network access — the host mediates all network calls (subject to `--allow-host` policy). ### Example ```go //go:wasmexport fetch_todo func fetchTodo() int32 { req := pdk.NewHTTPRequest(pdk.MethodGet, "https://jsonplaceholder.typicode.com/todos/1") req.SetHeader("Accept", "application/json") res := req.Send() if res.Status() != 200 { pdk.SetErrorString("unexpected status: " + strconv.Itoa(int(res.Status()))) return 1 } pdk.OutputMemory(res.Memory()) return 0 } ``` ``` -------------------------------- ### Declare Host Function Import in Go Source: https://github.com/extism/go-pdk/blob/main/README.md Declares an imported host function signature. The implementation is provided by the host environment. ```go //go:wasmimport extism:host/user a_python_func func aPythonFunc(uint64) uint64 ``` -------------------------------- ### pdk.LogMemory Source: https://context7.com/extism/go-pdk/llms.txt Logs a pre-allocated Memory block. Logs the content of an existing `Memory` block, avoiding an extra allocation when the string is already in host memory. ```APIDOC ## `pdk.LogMemory(level pdk.LogLevel, m pdk.Memory)` — Log a pre-allocated Memory block Logs the content of an existing `Memory` block, avoiding an extra allocation when the string is already in host memory. ### Example ```go //go:wasmexport log_input func logInput() int32 { mem := pdk.AllocateBytes(pdk.Input()) defer mem.Free() pdk.LogMemory(pdk.LogDebug, mem) pdk.OutputMemory(mem) return 0 } ``` ``` -------------------------------- ### Set HTTP Request Headers in Go Source: https://context7.com/extism/go-pdk/llms.txt Use `SetHeader` to add or modify HTTP request headers. Chaining calls is supported. ```go req := pdk.NewHTTPRequest(pdk.MethodPost, "https://api.example.com/events") req.SetHeader("Content-Type", "application/json"). SetHeader("Authorization", "Bearer " + token) ``` -------------------------------- ### Decoding Host Function Arguments Source: https://context7.com/extism/go-pdk/llms.txt Helper functions to decode typed values from raw Wasm memory offsets passed as arguments by the host to an imported function. ```APIDOC ## `pdk.ParamBytes` / `pdk.ParamString` / `pdk.ParamU32` / `pdk.ParamU64` — Read host-function arguments Helpers that decode typed values from raw Wasm memory offsets passed as arguments by the host to an imported function. ```go //go:wasmimport extism:host/user transform_string func transformString(inputOffset uint64) uint64 //go:wasmexport use_host_transform func useHostTransform() int32 { input := pdk.InputString() mem := pdk.AllocateString(input) defer mem.Free() resultOffset := transformString(mem.Offset()) result := pdk.ParamString(resultOffset) // decode the string at the returned offset pdk.OutputString(result) return 0 } ``` ``` -------------------------------- ### Deserialize Host Memory Block as JSON in Go Source: https://context7.com/extism/go-pdk/llms.txt Use `JSONFrom` to read a host memory block at a given offset and unmarshal it into a Go value. Returns an error if deserialization fails. ```go //go:wasmexport round_trip_json func roundTripJSON() int32 { type Payload struct{ Value string } orig := Payload{Value: "hello"} mem, _ := pdk.AllocateJSON(orig) var decoded Payload if err := pdk.JSONFrom(mem.Offset(), &decoded); err != nil { pdk.SetError(err) return 1 } pdk.OutputString(decoded.Value) // => hello return 0 } ``` -------------------------------- ### SetBody Source: https://context7.com/extism/go-pdk/llms.txt Attaches a byte slice as the HTTP request body. ```APIDOC ## (*pdk.HTTPRequest).SetBody(body []byte) *pdk.HTTPRequest ### Description Attaches a byte slice as the HTTP request body. ### Method (Implicitly part of HTTPRequest object) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **body** ([]byte) - Required - The byte slice to be used as the request body. ### Request Example ```go //go:wasmexport post_data func postData() int32 { payload := []byte(`{"event":"click","user":"alice"}`) req := pdk.NewHTTPRequest(pdk.MethodPost, "https://api.example.com/events") req.SetHeader("Content-Type", "application/json").SetBody(payload) res := req.Send() pdk.OutputString("posted, status: " + strconv.Itoa(int(res.Status()))) return 0 } ``` ### Response #### Success Response Returns the modified `*HTTPRequest` object for chaining. #### Response Example (Chained method call, no direct response to display) ``` -------------------------------- ### Generated Go Function Stub for Extism Plugin Source: https://github.com/extism/go-pdk/blob/main/README.md A Go function stub generated by XTP Bindgen. This function is intended to be implemented with the plugin's logic. It includes error handling for unimplemented functions. ```go package main // returns VowelReport (The result of counting vowels on the Vowels input.) func CountVowels(input string) (VowelReport, error) { // TODO: fill out your implementation here panic("Function not implemented.") } ``` -------------------------------- ### Log Messages from Wasm Plugin in Go Source: https://github.com/extism/go-pdk/blob/main/README.md Logs messages at different levels (Info, Debug, Warn, Error) using the Extism logging function. ```go //go:wasmexport log_stuff func logStuff() int32 { pdk.Log(pdk.LogInfo, "An info log!") pdk.Log(pdk.LogDebug, "A debug log!") pdk.Log(pdk.LogWarn, "A warn log!") pdk.Log(pdk.LogError, "An error log!") return 0 } ```