Skip to content

Commit fee38b4

Browse files
authored
feat(net/ghttp): enhance GetHeader method to support default values (#4210)
1 parent 69e3362 commit fee38b4

File tree

2 files changed

+20
-5
lines changed

2 files changed

+20
-5
lines changed

net/ghttp/ghttp_request.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,8 +151,13 @@ func (r *Request) IsExited() bool {
151151
}
152152

153153
// GetHeader retrieves and returns the header value with given `key`.
154-
func (r *Request) GetHeader(key string) string {
155-
return r.Header.Get(key)
154+
// It returns the optional `def` parameter if the header does not exist.
155+
func (r *Request) GetHeader(key string, def ...string) string {
156+
value := r.Header.Get(key)
157+
if value == "" && len(def) > 0 {
158+
value = def[0]
159+
}
160+
return value
156161
}
157162

158163
// GetHost returns current request host name, which might be a domain or an IP without port.

net/ghttp/ghttp_z_unit_feature_request_test.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,11 @@ func Test_Params_Basic(t *testing.T) {
363363
func Test_Params_Header(t *testing.T) {
364364
s := g.Server(guid.S())
365365
s.BindHandler("/header", func(r *ghttp.Request) {
366-
r.Response.Write(r.GetHeader("test"))
366+
r.Response.Write(map[string]interface{}{
367+
"without-def": r.GetHeader("no-header"),
368+
"with-def": r.GetHeader("no-header", "my-default"),
369+
"x-custom-with": r.GetHeader("x-custom", "my-default"),
370+
})
367371
})
368372
s.SetDumpRouterMap(false)
369373
s.Start()
@@ -374,8 +378,14 @@ func Test_Params_Header(t *testing.T) {
374378
prefix := fmt.Sprintf("http://127.0.0.1:%d", s.GetListenedPort())
375379
client := g.Client()
376380
client.SetPrefix(prefix)
377-
378-
t.Assert(client.Header(g.MapStrStr{"test": "123456"}).GetContent(ctx, "/header"), "123456")
381+
client.SetHeader("x-custom", "custom-value")
382+
383+
resp := client.GetContent(ctx, "/header")
384+
t.Assert(gjson.New(resp).Map(), g.Map{
385+
"without-def": "",
386+
"with-def": "my-default",
387+
"x-custom-with": "custom-value",
388+
})
379389
})
380390
}
381391

0 commit comments

Comments
 (0)