http_request_fixed.zip (2.6 KB)
The revised my_callback function.
// The C block function for Sketchup::Http::Request#start.
// It is invoked when the HTTP request completes.
// Parameters: argc (number of yielded values), argv (array of yielded values)
VALUE my_callback(VALUE yieldarg, VALUE data, int argc, const VALUE *argv, VALUE passed_block) {
// Get the persistent module for IVAR access
VALUE mLightUp = rb_const_get(rb_cObject, rb_intern("LightUp"));
VALUE mMyExtension = rb_const_get(mLightUp, rb_intern("MyExtension"));
// The block is expected to receive two arguments: [request, response].
// Check if the expected two arguments are present in argc/argv.
if (argc == 2) {
VALUE request_obj = argv[0]; // The Request object is the first argument
VALUE response_obj = argv[1]; // The Response object is the second argument
// Get status_code from the response object
VALUE status_code = rb_funcall(response_obj, rb_intern("status_code"), 0);
// Use FIX2INT for the comparison check
int status_int = FIX2INT(status_code);
char status_buffer[128];
if (status_int >= 200 && status_int < 300) {
// ✅ Success Branch: Print Status Code and Body Content
VALUE body = rb_funcall(response_obj, rb_intern("body"), 0);
// 1. Print status message
VALUE status_str = rb_inspect(status_code);
snprintf(status_buffer, sizeof(status_buffer), "✅ HTTP Request Succeeded! Status: %s", StringValueCStr(&status_str));
ruby_puts_cstr(status_buffer);
// 2. Print body length header
snprintf(status_buffer, sizeof(status_buffer), "--- Response Body (Length: %ld) ---", RSTRING_LEN(body));
ruby_puts_cstr(status_buffer);
// 3. Print the actual body content directly:
rb_funcall(rb_mKernel, rb_intern("puts"), 1, body);
ruby_puts_cstr("------------------------------------");
} else {
// ❌ Failure Branch: Get headers and call print_headers
VALUE headers = rb_funcall(response_obj, rb_intern("headers"), 0);
print_headers(status_code, headers);
}
// Store the response object on the persistent module
rb_ivar_set(mMyExtension, rb_intern("@response"), response_obj);
} else {
// Handle unexpected argument count
rb_warn("Callback did not receive the expected two arguments (request, response).");
}
// Clear the request reference on the persistent module
rb_ivar_set(mMyExtension, rb_intern("@request"), Qnil);
return Qnil;
}