Skip to content

Commit 59370fc

Browse files
committed
handle body
1 parent 05aa925 commit 59370fc

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

server/modules/http/http.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -446,6 +446,37 @@ func newRequest(runtime *sobek.Runtime, r *http.Request) sobek.Value {
446446
}
447447
reqObj.Set("headers", headersObj)
448448

449+
// Read request body
450+
bodyStr := ""
451+
if r.Body != nil {
452+
bodyBytes, err := io.ReadAll(r.Body)
453+
if err == nil {
454+
bodyStr = string(bodyBytes)
455+
}
456+
// Close the original body and replace with a new reader for downstream use
457+
r.Body.Close()
458+
r.Body = io.NopCloser(strings.NewReader(bodyStr))
459+
}
460+
461+
reqObj.Set("body", bodyStr)
462+
463+
// Add text() method for compatibility
464+
reqObj.Set("text", func(call sobek.FunctionCall) sobek.Value {
465+
return runtime.ToValue(bodyStr)
466+
})
467+
468+
// Add json() method for convenience
469+
reqObj.Set("json", func(call sobek.FunctionCall) sobek.Value {
470+
if bodyStr == "" {
471+
return sobek.Null()
472+
}
473+
jsonVal, err := runtime.RunString("JSON.parse(" + runtime.ToValue(bodyStr).String() + ")")
474+
if err != nil {
475+
panic(runtime.NewGoError(err))
476+
}
477+
return jsonVal
478+
})
479+
449480
return reqObj
450481
}
451482

0 commit comments

Comments
 (0)