Search code examples
http-headerscrystal-lang

What is the difference between `[]=` and `add` for HTTP::Server::Response#headers?


I looked at the source code for both []= and .add when adding/manipulating headers. I'm still confused as to the reason why there are two ways to add/set headers. What are the differences between the two methods?


Solution

  • []= replaces all header key content with a new array of value

    puts response.headers["Accept-Language"] # => ["de"]
    response.headers["Accept-Language"] = "de-CH" # or ["de-CH"]
    puts response.headers["Accept-Language"] # => ["de-CH"]
    

    .add checks if header key exist and append the value:

    puts response.headers["Accept-Language"] # => ["de"]
    response.headers.add "Accept-Language", "de-CH"
    puts response.headers["Accept-Language"] # => ["de", "de-CH"]