diff --git a/config/user-agent.yaml b/config/user-agent.yaml new file mode 100644 index 0000000..ca974dd --- /dev/null +++ b/config/user-agent.yaml @@ -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}}" + } + ] \ No newline at end of file diff --git a/vars/request.go b/vars/request.go index d2e3214..596120e 100644 --- a/vars/request.go +++ b/vars/request.go @@ -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 { @@ -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"] diff --git a/vars/request_test.go b/vars/request_test.go new file mode 100644 index 0000000..b0c7989 --- /dev/null +++ b/vars/request_test.go @@ -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) + } +}