From cf652fce1d39329976556a0e181945815a4aa3de Mon Sep 17 00:00:00 2001 From: zach Date: Tue, 15 Oct 2024 12:29:02 -0700 Subject: [PATCH] feat: make it possible to access http response headers (#47) --- env.go | 5 +++++ extism_pdk.go | 21 +++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/env.go b/env.go index cca8ab8..5416b45 100644 --- a/env.go +++ b/env.go @@ -120,6 +120,11 @@ func extismHTTPRequest(request, body extismPointer) extismPointer //go:wasmimport extism:host/env http_status_code func extismHTTPStatusCode() int32 +// extismHTTPHeaders returns the response headers for the last-sent `extism_http_request` call. +// +//go:wasmimport extism:host/env http_headers +func extismHTTPHeaders() extismPointer + // extismLogInfo logs an "info" string to the host from the previously-written UTF-8 string written to `offset`. // Note that the memory at `offset` can be immediately freed because it is immediately logged. // diff --git a/extism_pdk.go b/extism_pdk.go index 1d016fb..32914ba 100644 --- a/extism_pdk.go +++ b/extism_pdk.go @@ -312,8 +312,9 @@ type HTTPRequest struct { // HTTPResponse represents an HTTP response returned from the host. type HTTPResponse struct { - memory Memory - status uint16 + memory Memory + status uint16 + headers map[string]string } // Memory returns the memory associated with the `HTTPResponse`. @@ -337,6 +338,11 @@ func (r HTTPResponse) Status() uint16 { return r.status } +// Headers returns a map containing the HTTP response headers +func (r *HTTPResponse) Headers() map[string]string { + return r.headers +} + // HTTPMethod represents an HTTP method. type HTTPMethod int32 @@ -421,11 +427,22 @@ func (r *HTTPRequest) Send() HTTPResponse { length := extismLengthUnsafe(offset) status := uint16(extismHTTPStatusCode()) + headersOffs := extismHTTPHeaders() + headers := map[string]string{} + + if headersOffs != 0 { + length := extismLengthUnsafe(headersOffs) + mem := Memory{offset: headersOffs, length: length} + defer mem.Free() + json.Unmarshal(mem.ReadBytes(), &headers) + } + memory := Memory{offset, length} return HTTPResponse{ memory, status, + headers, } }