Skip to content

Commit

Permalink
[ADD] get request headers to params (#65)
Browse files Browse the repository at this point in the history
  • Loading branch information
mrgleam authored and jmartin82 committed Sep 17, 2018
1 parent 409231e commit 9e99dc1
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 0 deletions.
14 changes: 14 additions & 0 deletions config/user-agent.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
request:
method: GET
path: /user-agent
response:
statusCode: 200
headers:
Content-Type:
- "application/json"
body: >
[
{
"user_agent":"{{request.header.User-Agent}}"
}
]
15 changes: 15 additions & 0 deletions vars/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ func (rp Request) Fill(holders []string) map[string]string {
s, found = rp.getPathParam(tag[13:])
} else if strings.HasPrefix(tag, "request.cookie.") {
s, found = rp.getCookieParam(tag[15:])
} else if strings.HasPrefix(tag, "request.header.") {
s, found = rp.getHeaderParam(tag[15:])
}

if found {
Expand Down Expand Up @@ -145,6 +147,19 @@ func (rp Request) getCookieParam(name string) (string, bool) {
return value, true
}

func (rp Request) getHeaderParam(name string) (string, bool) {

value, f := rp.Request.HttpHeaders.Headers[name]
if !f || len(rp.Request.HttpHeaders.Headers) == 0 {
return "", false
}
if len(value) == 0 {
return "", false
}

return value[0], true
}

func (rp Request) getBodyParam(name string) (string, bool) {

contentType, found := rp.Request.Headers["Content-Type"]
Expand Down
55 changes: 55 additions & 0 deletions vars/request_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package vars

import (
"strings"
"testing"

"github.com/jmartin82/mmock/definition"
)

func TestGetHeaderParam(t *testing.T) {
rp := Request{}
header := make(definition.Values)
header["Authorization"] = []string{"Bearer abc123"}
req := definition.Request{}
req.Headers = header
rp.Request = &req
v, f := rp.getHeaderParam("Authorization")
if !f {
t.Errorf("Header key not found")
}

if !strings.EqualFold(v, "Bearer abc123") {
t.Errorf("Couldn't get the content. Value: %s", v)
}
}

func TestGetHeaderParamNotFoundHeaderKey(t *testing.T) {
rp := Request{}
header := make(definition.Values)
header["Authorization"] = []string{"Bearer abc123"}
req := definition.Request{}
req.Headers = header
rp.Request = &req
_, f := rp.getHeaderParam("Authorization2")
if f {
t.Errorf("Header key found")
}
}

func TestGetHeaderParamWithOutHeaderValue(t *testing.T) {
rp := Request{}
header := make(definition.Values)
header["Authorization"] = []string{}
req := definition.Request{}
req.Headers = header
rp.Request = &req
v, f := rp.getHeaderParam("Authorization")
if f {
t.Errorf("Header key found")
}

if strings.EqualFold(v, "Bearer abc1235") {
t.Errorf("Couldn get the content. Value: %s", v)
}
}

0 comments on commit 9e99dc1

Please sign in to comment.