From c4cc907433a3ac2e5373cb0190ece145bfc047bb Mon Sep 17 00:00:00 2001 From: flywind <43030857+xflywind@users.noreply.github.com> Date: Thu, 5 Nov 2020 21:01:28 +0800 Subject: [PATCH] fix adding empty sequence to HTTP headers (#15783) * fix adding empty sequence to HTTP headers * add tests --- lib/pure/httpcore.nim | 11 +++++++---- tests/stdlib/thttpcore.nim | 27 +++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/lib/pure/httpcore.nim b/lib/pure/httpcore.nim index af1bfc0883..d796c788d9 100644 --- a/lib/pure/httpcore.nim +++ b/lib/pure/httpcore.nim @@ -166,9 +166,12 @@ proc `[]=`*(headers: HttpHeaders, key, value: string) = proc `[]=`*(headers: HttpHeaders, key: string, value: seq[string]) = ## Sets the header entries associated with ``key`` to the specified list of - ## values. - ## Replaces any existing values. - headers.table[headers.toCaseInsensitive(key)] = value + ## values. Replaces any existing values. If ``value`` is empty, + ## deletes the header entries associated with ``key``. + if value.len > 0: + headers.table[headers.toCaseInsensitive(key)] = value + else: + headers.table.del(headers.toCaseInsensitive(key)) proc add*(headers: HttpHeaders, key, value: string) = ## Adds the specified value to the specified key. Appends to any existing @@ -179,7 +182,7 @@ proc add*(headers: HttpHeaders, key, value: string) = headers.table[headers.toCaseInsensitive(key)].add(value) proc del*(headers: HttpHeaders, key: string) = - ## Delete the header entries associated with ``key`` + ## Deletes the header entries associated with ``key`` headers.table.del(headers.toCaseInsensitive(key)) iterator pairs*(headers: HttpHeaders): tuple[key, value: string] = diff --git a/tests/stdlib/thttpcore.nim b/tests/stdlib/thttpcore.nim index 33c24453ed..cb1a0875fb 100644 --- a/tests/stdlib/thttpcore.nim +++ b/tests/stdlib/thttpcore.nim @@ -51,3 +51,30 @@ suite "httpcore": doAssert parseHeader("Accept: foo, bar") == (key: "Accept", value: @["foo", "bar"]) doAssert parseHeader("Accept: foo, bar, prologue") == (key: "Accept", value: @["foo", "bar", "prologue"]) doAssert parseHeader("Accept: foo, bar, prologue, starlight") == (key: "Accept", value: @["foo", "bar", "prologue", "starlight"]) + + test "add empty sequence to HTTP headers": + block: + var headers = newHttpHeaders() + headers["empty"] = @[] + + doAssert not headers.hasKey("empty") + + block: + var headers = newHttpHeaders() + headers["existing"] = "true" + headers["existing"] = @[] + + doAssert not headers.hasKey("existing") + + block: + var headers = newHttpHeaders() + headers["existing"] = @["true"] + headers["existing"] = @[] + + doAssert not headers.hasKey("existing") + + block: + var headers = newHttpHeaders() + headers["existing"] = @[] + headers["existing"] = @["true"] + doAssert headers.hasKey("existing")