Skip to content

Commit

Permalink
feat: make it possible to access http response headers
Browse files Browse the repository at this point in the history
  • Loading branch information
zshipko committed Oct 11, 2024
1 parent 49215e0 commit 787ee5a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 2 deletions.
5 changes: 5 additions & 0 deletions env.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
//
Expand Down
21 changes: 19 additions & 2 deletions extism_pdk.go
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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

Expand Down Expand Up @@ -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,
}
}

Expand Down

0 comments on commit 787ee5a

Please sign in to comment.