From 2d40891d612adf1709699e581f4b2f7756189e33 Mon Sep 17 00:00:00 2001
From: He Li
Date: Thu, 31 Oct 2024 10:01:03 +0800
Subject: [PATCH] feat: AddHeader function that appends the headers list
---
hijack.go | 12 ++++++++++++
hijack_test.go | 2 ++
2 files changed, 14 insertions(+)
diff --git a/hijack.go b/hijack.go
index 1a2181df..a3d0d911 100644
--- a/hijack.go
+++ b/hijack.go
@@ -378,6 +378,18 @@ func (ctx *HijackResponse) SetHeader(pairs ...string) *HijackResponse {
return ctx
}
+// Append key-value pairs to the end of the response headers.
+// 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],
+ Value: pairs[i+1],
+ })
+ }
+ return ctx
+}
+
// SetBody of the payload, if obj is []byte or string, raw body will be used, else it will be encoded as json.
func (ctx *HijackResponse) SetBody(obj interface{}) *HijackResponse {
switch body := obj.(type) {
diff --git a/hijack_test.go b/hijack_test.go
index a5b114ab..470fd8ce 100644
--- a/hijack_test.go
+++ b/hijack_test.go
@@ -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