Skip to content

Commit

Permalink
feat: support add/set request header function
Browse files Browse the repository at this point in the history
  • Loading branch information
vicanso committed Apr 1, 2019
1 parent dad5574 commit 5450ba6
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
15 changes: 15 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,21 @@ func (c *Context) GetRequestHeader(key string) string {
return c.Request.Header.Get(key)
}

// SetRequestHeader set http request header
func (c *Context) SetRequestHeader(key, value string) {
h := c.Request.Header
if value == "" {
h.Del(key)
return
}
h.Set(key, value)
}

// AddRequestHeader add http request header
func (c *Context) AddRequestHeader(key, value string) {
c.Request.Header.Add(key, value)
}

// Header get headers of http response
func (c *Context) Header() http.Header {
return c.Headers
Expand Down
22 changes: 22 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,28 @@ func TestGetSetHeader(t *testing.T) {
}
})

t.Run("set header to request", func(t *testing.T) {
key := "X-Request-ID"
value := "1"
if c.GetRequestHeader(key) != "" {
t.Fatalf("request id should be nil before set")
}
c.SetRequestHeader(key, value)
if c.GetRequestHeader(key) != value {
t.Fatalf("set request header fail")
}
})

t.Run("add header to request", func(t *testing.T) {
key := "X-Request-Type"
c.AddRequestHeader(key, "1")
c.AddRequestHeader(key, "2")
ids := c.Request.Header[key]
if strings.Join(ids, ",") != "1,2" {
t.Fatalf("add request header fail")
}
})

t.Run("set header to the response", func(t *testing.T) {
c.SetHeader("X-Response-Id", "1")
if c.GetHeader("X-Response-Id") != "1" {
Expand Down

0 comments on commit 5450ba6

Please sign in to comment.