File tree Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Expand file tree Collapse file tree 2 files changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -356,6 +356,31 @@ func (ctx *HijackResponse) Headers() http.Header {
356356
357357// SetHeader of the payload via key-value pairs.
358358func (ctx * HijackResponse ) SetHeader (pairs ... string ) * HijackResponse {
359+ headerIndex := make (map [string ]int , len (ctx .payload .ResponseHeaders ))
360+ for i , header := range ctx .payload .ResponseHeaders {
361+ headerIndex [header .Name ] = i
362+ }
363+
364+ for i := 0 ; i < len (pairs ); i += 2 {
365+ name := pairs [i ]
366+ value := pairs [i + 1 ]
367+
368+ if idx , exists := headerIndex [name ]; exists {
369+ ctx .payload .ResponseHeaders [idx ].Value = value
370+ } else {
371+ ctx .payload .ResponseHeaders = append (ctx .payload .ResponseHeaders , & proto.FetchHeaderEntry {
372+ Name : name ,
373+ Value : value ,
374+ })
375+ headerIndex [name ] = len (ctx .payload .ResponseHeaders ) - 1
376+ }
377+ }
378+ return ctx
379+ }
380+
381+ // AddHeader appends key-value pairs to the end of the response headers.
382+ // Duplicate keys will be preserved.
383+ func (ctx * HijackResponse ) AddHeader (pairs ... string ) * HijackResponse {
359384 for i := 0 ; i < len (pairs ); i += 2 {
360385 ctx .payload .ResponseHeaders = append (ctx .payload .ResponseHeaders , & proto.FetchHeaderEntry {
361386 Name : pairs [i ],
Original file line number Diff line number Diff line change @@ -75,6 +75,8 @@ func TestHijack(t *testing.T) {
7575 g .Has (ctx .Response .Headers ().Get ("Content-Type" ), "text/html; charset=utf-8" )
7676
7777 // override response header
78+ ctx .Response .AddHeader ("Set-Cookie" , "key=val1" )
79+ // This should override the previous one
7880 ctx .Response .SetHeader ("Set-Cookie" , "key=val" )
7981
8082 // override response body
You can’t perform that action at this time.
0 commit comments