From fdc264e6d5049b92f7ceb41c337564df72cafe79 Mon Sep 17 00:00:00 2001 From: Jacob Quinn Date: Thu, 25 Jan 2018 10:11:17 -0700 Subject: [PATCH] Re-implement automatic Content-Type detection using the sniff algorithm (#175) --- src/ContentTypeRequest.jl | 27 +++++++++++++++++++++++++++ src/HTTP.jl | 7 +++++-- 2 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 src/ContentTypeRequest.jl diff --git a/src/ContentTypeRequest.jl b/src/ContentTypeRequest.jl new file mode 100644 index 000000000..a87087a61 --- /dev/null +++ b/src/ContentTypeRequest.jl @@ -0,0 +1,27 @@ +module ContentTypeDetection + +import ..Layer, ..request +using ..URIs +using ..Pairs: getkv, setkv +import ..sniff +import ..Form +using ..Messages +import ..MessageRequest: bodylength, bodybytes +import ..@debug, ..DEBUG_LEVEL + +abstract type ContentTypeDetectionLayer{Next <: Layer} <: Layer end +export ContentTypeDetectionLayer + +function request(::Type{ContentTypeDetectionLayer{Next}}, + method::String, url::URI, headers, body; kw...) where Next + + if getkv(headers, "Content-Type", "") == "" && + !isa(body, Form) && bodylength(body) != unknown_length && bodylength(body) > 0 + sn = sniff(bodybytes(body)) + setkv(headers, "Content-Type", sn) + @debug 1 "setting Content-Type header to: $sn" + end + return request(Next, method, url, headers, body; kw...) +end + +end # module diff --git a/src/HTTP.jl b/src/HTTP.jl index 7a7a137cf..8a8af227f 100644 --- a/src/HTTP.jl +++ b/src/HTTP.jl @@ -20,6 +20,7 @@ include("Strings.jl") include("URIs.jl") ;using .URIs include("utils.jl") include("fifobuffer.jl") ;using .FIFOBuffers +include("sniff.jl") include("cookies.jl") ;using .Cookies include("multipart.jl") include("Parsers.jl") ;import .Parsers: Parser, Headers, Header, @@ -439,6 +440,7 @@ include("ExceptionRequest.jl"); using .ExceptionRequest include("RetryRequest.jl"); using .RetryRequest include("ConnectionRequest.jl"); using .ConnectionRequest include("StreamRequest.jl"); using .StreamRequest +include("ContentTypeRequest.jl"); using .ContentTypeDetection """ The `stack()` function returns the default HTTP Layer-stack type. @@ -559,12 +561,14 @@ function stack(;redirect=true, retry=true, status_exception=true, readtimeout=0, + detect_content_type=true, kw...) NoLayer = Union (redirect ? RedirectLayer : NoLayer){ (basic_authorization ? BasicAuthLayer : NoLayer){ + (detect_content_type ? ContentTypeDetectionLayer : NoLayer){ (cookies ? CookieLayer : NoLayer){ (canonicalize_headers ? CanonicalizeLayer : NoLayer){ MessageLayer{ @@ -574,12 +578,11 @@ function stack(;redirect=true, ConnectionPoolLayer{ (readtimeout > 0 ? TimeoutLayer : NoLayer){ StreamLayer - }}}}}}}}}} + }}}}}}}}}}} end include("client.jl") -include("sniff.jl") include("Handlers.jl") ;using .Handlers include("Servers.jl") ;using .Servers; using .Servers: listen Base.@deprecate_binding(Nitrogen, Servers, false)