From c4d727cbe684877eaa334fee804b0601e9e4e74c Mon Sep 17 00:00:00 2001 From: An Tao Date: Fri, 14 Aug 2020 08:10:56 +0800 Subject: [PATCH] Fix compilation warning of sprintf function (#537) --- lib/src/HttpRequestImpl.cc | 2 +- lib/src/HttpResponseImpl.cc | 5 +++-- lib/src/HttpUtils.h | 30 ++++++++++++++++++++++++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/lib/src/HttpRequestImpl.cc b/lib/src/HttpRequestImpl.cc index ed67dbea3f..fe71416c45 100644 --- a/lib/src/HttpRequestImpl.cc +++ b/lib/src/HttpRequestImpl.cc @@ -316,7 +316,7 @@ void HttpRequestImpl::appendToBuffer(trantor::MsgBuffer *output) const char buf[64]; auto len = snprintf(buf, sizeof(buf), - "Content-Length: %lu\r\n", + contentLengthFormatString(), content.length() + content_.length()); output->append(buf, len); if (contentTypeString_.empty()) diff --git a/lib/src/HttpResponseImpl.cc b/lib/src/HttpResponseImpl.cc index ecebdec3b7..abd8a17240 100644 --- a/lib/src/HttpResponseImpl.cc +++ b/lib/src/HttpResponseImpl.cc @@ -30,6 +30,7 @@ using namespace drogon; namespace drogon { + // "Fri, 23 Aug 2019 12:58:03 GMT" length = 29 static const size_t httpFullDateStringLength = 29; static inline void doResponseCreateAdvices( @@ -272,7 +273,7 @@ void HttpResponseImpl::makeHeaderString(trantor::MsgBuffer &buffer) auto bodyLength = bodyPtr_ ? bodyPtr_->length() : 0; len = snprintf(buffer.beginWrite(), buffer.writableBytes(), - "Content-Length: %lu\r\n", + contentLengthFormatString(), bodyLength); } else @@ -285,7 +286,7 @@ void HttpResponseImpl::makeHeaderString(trantor::MsgBuffer &buffer) } len = snprintf(buffer.beginWrite(), buffer.writableBytes(), - "Content-Length: %lld\r\n", + contentLengthFormatString(), filestat.st_size); } buffer.hasWritten(len); diff --git a/lib/src/HttpUtils.h b/lib/src/HttpUtils.h index 5990048832..26691b97db 100644 --- a/lib/src/HttpUtils.h +++ b/lib/src/HttpUtils.h @@ -25,4 +25,34 @@ ContentType parseContentType(const string_view &contentType); const string_view &webContentTypeToString(ContentType contenttype); const string_view &statusCodeToString(int code); ContentType getContentType(const std::string &fileName); +template +inline constexpr const char *contentLengthFormatString() +{ + return "Content-Length: %d\r\n"; +} +template <> +inline constexpr const char *contentLengthFormatString() +{ + return "Content-Length: %u\r\n"; +} +template <> +inline constexpr const char *contentLengthFormatString() +{ + return "Content-Length: %ld\r\n"; +} +template <> +inline constexpr const char *contentLengthFormatString() +{ + return "Content-Length: %lu\r\n"; +} +template <> +inline constexpr const char *contentLengthFormatString() +{ + return "Content-Length: %lld\r\n"; +} +template <> +inline constexpr const char *contentLengthFormatString() +{ + return "Content-Length: %llu\r\n"; +} } // namespace drogon