util: create IsJSON/IsHTML type helper

This commit is contained in:
ycdesu 2021-02-06 10:43:25 +08:00
parent 565086cc2a
commit 8663704d6e
2 changed files with 46 additions and 0 deletions

View File

@ -40,3 +40,19 @@ func (r *Response) DecodeJSON(o interface{}) error {
func (r *Response) IsError() bool {
return r.StatusCode >= 400
}
func (r *Response) IsJSON() bool {
switch r.Header.Get("content-type") {
case "text/json", "application/json", "application/json; charset=utf-8":
return true
}
return false
}
func (r *Response) IsHTML() bool {
switch r.Header.Get("content-type") {
case "text/html":
return true
}
return false
}

View File

@ -42,3 +42,33 @@ func TestResponse_IsError(t *testing.T) {
assert.Equal(t, isErr, resp.IsError())
}
}
func TestResponse_IsJSON(t *testing.T) {
cases := map[string]bool{
"text/json": true,
"application/json": true,
"application/json; charset=utf-8": true,
"text/html": false,
}
for k, v := range cases {
resp := &Response{Response: &http.Response{}}
resp.Header = http.Header{}
resp.Header.Set("content-type", k)
assert.Equal(t, v, resp.IsJSON())
}
}
func TestResponse_IsHTML(t *testing.T) {
cases := map[string]bool{
"text/json": false,
"application/json": false,
"application/json; charset=utf-8": false,
"text/html": true,
}
for k, v := range cases {
resp := &Response{Response: &http.Response{}}
resp.Header = http.Header{}
resp.Header.Set("content-type", k)
assert.Equal(t, v, resp.IsHTML())
}
}