Skip to content

🛠️ Host functions

hostGetEnv

hostGetEnv: read an environment variable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main

import (
    "github.com/extism/go-pdk"
)

//export hostPrintln
func hostPrintln(offset uint64) uint64

func Println(text string) {
    memoryText := pdk.AllocateString(text)
    hostPrintln(memoryText.Offset())
}

//export hostGetEnv
func hostGetEnv(offset uint64) uint64

func GetEnv(name string) string {
    // copy the name of the environment variable to the shared memory
    variableName := pdk.AllocateString(name)
    // call the host function
    offset := hostGetEnv(variableName.Offset())

    // read the value of the result from the shared memory
    variableValue := pdk.FindMemory(offset)
    buffer := make([]byte, variableValue.Length())
    variableValue.Load(buffer)

    // cast the buffer to string and return the value
    envVarValue := string(buffer)
    return envVarValue
}

//export hello
func hello() uint64 {
    message := GetEnv("MESSAGE")
    Println("🤖 MESSAGE=" + message)

    return 0
}

func main() {}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use extism_pdk::*;

extern "C" {
    fn hostPrintln(ptr: u64) -> u64;
}

pub fn println(text: String) {
    let mut memory_text: Memory = extism_pdk::Memory::new(text.len());
    memory_text.store(text);
    unsafe { hostPrintln(memory_text.offset) };
}

extern "C" {
    fn hostGetEnv(ptr: u64) -> u64;
}

pub fn get_env(name: String) -> String {
    // copy the name of the environment variable to the shared memory
    let mut variable_name: Memory = extism_pdk::Memory::new(name.len());
    variable_name.store(name);

    // call the host function
    let offset: u64 = unsafe { hostGetEnv(variable_name.offset) };

    // read the value of the result from the shared memory
    let variable_value: Memory = extism_pdk::Memory::find(offset).unwrap();

    // return the value
    return variable_value.to_string().unwrap()
}

#[plugin_fn]
pub fn hello(_: String) -> FnResult<u64> {

    let message : String = get_env("MESSAGE".to_string());

    println("🦀 MESSAGE=".to_string() + &message);

    Ok(0)
}