Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SetHeader should replace entries with the same key #1134

Merged
merged 3 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions hijack.go
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,31 @@

// SetHeader of the payload via key-value pairs.
func (ctx *HijackResponse) SetHeader(pairs ...string) *HijackResponse {
headerIndex := make(map[string]int, len(ctx.payload.ResponseHeaders))
for i, header := range ctx.payload.ResponseHeaders {
headerIndex[header.Name] = i
}

for i := 0; i < len(pairs); i += 2 {
name := pairs[i]
value := pairs[i+1]

if idx, exists := headerIndex[name]; exists {
ctx.payload.ResponseHeaders[idx].Value = value
} else {
ctx.payload.ResponseHeaders = append(ctx.payload.ResponseHeaders, &proto.FetchHeaderEntry{
Name: name,
Value: value,
})
headerIndex[name] = len(ctx.payload.ResponseHeaders) - 1
}
}
return ctx
}

// Append key-value pairs to the end of the response headers.

Check failure on line 381 in hijack.go

View workflow job for this annotation

GitHub Actions / test-linux

exported: comment on exported method HijackResponse.AddHeader should be of the form "AddHeader ..." (revive)
// Duplicate keys will be preserved.
func (ctx *HijackResponse) AddHeader(pairs ...string) *HijackResponse {
for i := 0; i < len(pairs); i += 2 {
ctx.payload.ResponseHeaders = append(ctx.payload.ResponseHeaders, &proto.FetchHeaderEntry{
Name: pairs[i],
Expand Down
2 changes: 2 additions & 0 deletions hijack_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ func TestHijack(t *testing.T) {
g.Has(ctx.Response.Headers().Get("Content-Type"), "text/html; charset=utf-8")

// override response header
ctx.Response.AddHeader("Set-Cookie", "key=val1")
// This should override the previous one
ctx.Response.SetHeader("Set-Cookie", "key=val")

// override response body
Expand Down
Loading