From fee38b4531224b929c095ef643a68a92bbad3d4b Mon Sep 17 00:00:00 2001 From: hailaz <739476267@qq.com> Date: Tue, 25 Mar 2025 20:42:30 +0800 Subject: [PATCH] feat(net/ghttp): enhance GetHeader method to support default values (#4210) --- net/ghttp/ghttp_request.go | 9 +++++++-- net/ghttp/ghttp_z_unit_feature_request_test.go | 14 ++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/net/ghttp/ghttp_request.go b/net/ghttp/ghttp_request.go index e17857f44..6bb4f622d 100644 --- a/net/ghttp/ghttp_request.go +++ b/net/ghttp/ghttp_request.go @@ -151,8 +151,13 @@ func (r *Request) IsExited() bool { } // GetHeader retrieves and returns the header value with given `key`. -func (r *Request) GetHeader(key string) string { - return r.Header.Get(key) +// It returns the optional `def` parameter if the header does not exist. +func (r *Request) GetHeader(key string, def ...string) string { + value := r.Header.Get(key) + if value == "" && len(def) > 0 { + value = def[0] + } + return value } // GetHost returns current request host name, which might be a domain or an IP without port. diff --git a/net/ghttp/ghttp_z_unit_feature_request_test.go b/net/ghttp/ghttp_z_unit_feature_request_test.go index bc60d8f50..fb200d938 100644 --- a/net/ghttp/ghttp_z_unit_feature_request_test.go +++ b/net/ghttp/ghttp_z_unit_feature_request_test.go @@ -363,7 +363,11 @@ func Test_Params_Basic(t *testing.T) { func Test_Params_Header(t *testing.T) { s := g.Server(guid.S()) s.BindHandler("/header", func(r *ghttp.Request) { - r.Response.Write(r.GetHeader("test")) + r.Response.Write(map[string]interface{}{ + "without-def": r.GetHeader("no-header"), + "with-def": r.GetHeader("no-header", "my-default"), + "x-custom-with": r.GetHeader("x-custom", "my-default"), + }) }) s.SetDumpRouterMap(false) s.Start() @@ -374,8 +378,14 @@ func Test_Params_Header(t *testing.T) { prefix := fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort()) client := g.Client() client.SetPrefix(prefix) + client.SetHeader("x-custom", "custom-value") - t.Assert(client.Header(g.MapStrStr{"test": "123456"}).GetContent(ctx, "/header"), "123456") + resp := client.GetContent(ctx, "/header") + t.Assert(gjson.New(resp).Map(), g.Map{ + "without-def": "", + "with-def": "my-default", + "x-custom-with": "custom-value", + }) }) }