From f3f401a79429e738272c9155e55f8f8ec8ce2c5b Mon Sep 17 00:00:00 2001 From: Struma Date: Sun, 28 Mar 2021 15:26:08 -0400 Subject: [PATCH] set HTTP response body encoding based on Content-Type --- binding/binding-util.h | 1 + binding/http-binding.cpp | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/binding/binding-util.h b/binding/binding-util.h index c7dc4210..50142bf9 100644 --- a/binding/binding-util.h +++ b/binding/binding-util.h @@ -170,6 +170,7 @@ return Data_Wrap_Struct(klass, 0, free, 0); \ #if RAPI_MINOR < 9 #define rb_utf8_str_new_cstr rb_str_new2 +#define rb_utf8_str_new rb_str_new #endif #define PRIsVALUE "s" diff --git a/binding/http-binding.cpp b/binding/http-binding.cpp index 1b6eb064..df104e7f 100644 --- a/binding/http-binding.cpp +++ b/binding/http-binding.cpp @@ -38,6 +38,25 @@ mkxp_net::StringMap hash2StringMap(VALUE hash) { return ret; } +VALUE getResponseBody(mkxp_net::HTTPResponse &res) { +#if RAPI_FULL >= 190 + auto it = res.headers().find("Content-Type"); + if (it == res.headers().end()) + return rb_str_new(res.body().c_str(), res.body().length()); + + std::string &ctype = it->second; + + if (!ctype.compare("text/plain") || !ctype.compare("application/json") || + !ctype.compare("application/xml") || !ctype.compare("text/html") || + !ctype.compare("text/css") || !ctype.compare("text/javascript") || + !ctype.compare("application/x-sh") || !ctype.compare("image/svg+xml") || + !ctype.compare("application/x-httpd-php")) + return rb_utf8_str_new(res.body().c_str(), res.body().length()); + +#endif + return rb_str_new(res.body().c_str(), res.body().length()); +} + RB_METHOD(httpGet) { RB_UNUSED_PARAM; @@ -56,7 +75,7 @@ RB_METHOD(httpGet) { auto res = req.get(); ret = rb_hash_new(); rb_hash_aset(ret, ID2SYM(rb_intern("status")), INT2NUM(res.status())); - rb_hash_aset(ret, ID2SYM(rb_intern("body")), rb_utf8_str_new(res.body().c_str(), res.body().length())); + rb_hash_aset(ret, ID2SYM(rb_intern("body")), getResponseBody(res)); rb_hash_aset(ret, ID2SYM(rb_intern("headers")), stringMap2hash(res.headers())); } catch (Exception &e) { raiseRbExc(e);