Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support reading http response headers #39

Merged
merged 10 commits into from
Nov 22, 2024
Merged
Prev Previous commit
chore: try different host for testing
nilslice committed Nov 22, 2024
commit 474e905b865a55ffe686db7b317ba43fbc1cc0c1
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -77,5 +77,5 @@ jobs:
COUNT=$(echo $TEST | jq | grep "I'm the inner struct" | wc -l)
test $COUNT -eq 3

TEST=$(extism call zig-out/bin/basic-example.wasm http_get --input '' --allow-host jsonplaceholder.typicode.com --enable-http-response-headers --log-level debug 2>&1)
echo $TEST | grep "application/json; charset=utf-8"
TEST=$(extism call zig-out/bin/basic-example.wasm http_headers --input '' --allow-host github.com --enable-http-response-headers --log-level debug 2>&1)
echo $TEST | grep "text/html"
39 changes: 29 additions & 10 deletions examples/basic.zig
Original file line number Diff line number Diff line change
@@ -135,16 +135,6 @@ export fn http_get() i32 {
plugin.setError("request failed");
return @as(i32, res.status);
}
var headers = res.headers(plugin.allocator) catch |err| {
plugin.setErrorFmt("err: {any}, failed to get headers from response!", .{err}) catch unreachable;
return -1;
};
defer headers.deinit();

const content_type = headers.get("content-type");
if (content_type) |t| {
plugin.log(.Debug, t.value); // something like 'application/json; charset=utf-8'
}

// get the bytes for the res body
const body = res.body(allocator) catch unreachable;
@@ -173,6 +163,35 @@ export fn http_get() i32 {
return 0;
}

export fn http_headers() i32 {
const plugin = Plugin.init(allocator);

var req = http.HttpRequest.init("GET", "https://github.com");
defer req.deinit(allocator);

const res = plugin.request(req, null) catch unreachable;
defer res.deinit();

if (res.status != 200) {
plugin.setError("request failed");
return @as(i32, res.status);
}
var headers = res.headers(plugin.allocator) catch |err| {
plugin.setErrorFmt("err: {any}, failed to get headers from response!", .{err}) catch unreachable;
return -1;
};
defer headers.deinit();

const content_type = headers.get("content-type");
if (content_type) |t| {
plugin.logFmt(.Debug, "got content-type: {s}", .{t.value}) catch unreachable;
} else {
return 1;
}

return 0;
}

export fn greet() i32 {
const plugin = Plugin.init(allocator);
const user = plugin.getConfig("user") catch unreachable orelse {