Skip to content

Commit

Permalink
Add a TryAdd method to RequestHeaders and use it
Browse files Browse the repository at this point in the history
  • Loading branch information
andreaTP committed Oct 4, 2023
1 parent b612c85 commit ac7c6f0
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 4 deletions.
16 changes: 13 additions & 3 deletions request_headers.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
package abstractions

//RequestHeaders represents a collection of request headers
// RequestHeaders represents a collection of request headers
type RequestHeaders struct {
header
}

//NewRequestHeaders creates a new RequestHeaders
// NewRequestHeaders creates a new RequestHeaders
func NewRequestHeaders() *RequestHeaders {
return &RequestHeaders{
header{make(map[string]map[string]struct{})},
}
}

//AddAll adds all headers from the other headers
// AddAll adds all headers from the other headers
func (r *RequestHeaders) AddAll(other *RequestHeaders) {
if other == nil || other.headers == nil {
return
Expand All @@ -23,3 +23,13 @@ func (r *RequestHeaders) AddAll(other *RequestHeaders) {
}
}
}

// TryAdd adds the header if it's not already present
func (r *RequestHeaders) TryAdd(key string, value string) bool {
if r.ContainsKey(key) {
return false
}

r.Add(key, value)
return true
}
17 changes: 17 additions & 0 deletions request_headers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ func TestIdAdds(t *testing.T) {
assert.Equal(t, "value", instance.Get("key")[0])
}

func TestIdTryAdds(t *testing.T) {
instance := NewRequestHeaders()
assert.NotNil(t, instance)
assert.True(t, instance.TryAdd("key", "value"))
assert.True(t, instance.ContainsKey("key"))
assert.Equal(t, "value", instance.Get("key")[0])
}

func TestItRemoves(t *testing.T) {
instance := NewRequestHeaders()
assert.NotNil(t, instance)
Expand Down Expand Up @@ -72,6 +80,15 @@ func TestItAddsAll(t *testing.T) {
assert.Equal(t, "value", instance.Get("key")[0])
}

func TestItTryAdds(t *testing.T) {
instance := NewRequestHeaders()
assert.NotNil(t, instance)
assert.True(t, instance.TryAdd("key", "value"))
assert.True(t, instance.ContainsKey("key"))
assert.False(t, instance.TryAdd("key", "value2"))
assert.Equal(t, "value", instance.Get("key")[0])
}

func TestIdListKeys(t *testing.T) {
instance := NewRequestHeaders()
assert.NotNil(t, instance)
Expand Down
2 changes: 1 addition & 1 deletion request_information.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ func (request *RequestInformation) setContentAndContentType(writer s.Serializati
}
request.Content = content
if request.Headers != nil {
request.Headers.Add(contentTypeHeader, contentType)
request.Headers.TryAdd(contentTypeHeader, contentType)
}
return nil
}
Expand Down

0 comments on commit ac7c6f0

Please sign in to comment.