From f32beffd333b771fba791b9d60abcced5dd88238 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roberto=20Abdelkader=20Mart=C3=ADnez=20P=C3=A9rez?= Date: Wed, 2 Oct 2019 16:20:39 +0200 Subject: [PATCH] New function GetReason to get HTTP reason phrase from an http.Request --- http/reason.go | 14 +++++++++++++ http/reason_test.go | 48 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 http/reason.go create mode 100644 http/reason_test.go diff --git a/http/reason.go b/http/reason.go new file mode 100644 index 0000000..458adf9 --- /dev/null +++ b/http/reason.go @@ -0,0 +1,14 @@ +package http + +import ( + "net/http" + "strings" +) + +func GetReason(r *http.Response) string { + if i := strings.IndexByte(r.Status, ' '); i != -1 { + return r.Status[i+1:] + } else { + return "" + } +} diff --git a/http/reason_test.go b/http/reason_test.go new file mode 100644 index 0000000..6a1521e --- /dev/null +++ b/http/reason_test.go @@ -0,0 +1,48 @@ +package http + +import ( + nethttp "net/http" + "testing" +) + +func TestEmptyStringIsEmptyReason(t *testing.T) { + r := &nethttp.Response{Status: ""} + if GetReason(r) != "" { + t.Errorf("We consider an empty status line to have an empty reason") + } +} + +func TestOnlyCodeIsEmptyReason(t *testing.T) { + r := &nethttp.Response{Status: "200"} + if GetReason(r) != "" { + t.Errorf("We consider an status line with just the status code to have an empty reason") + } +} + +func TestOnlyCodePlusSpaceIsEmptyReason(t *testing.T) { + r := &nethttp.Response{Status: "200 "} + if GetReason(r) != "" { + t.Errorf("We consider an status line with just the status code to have an empty reason") + } +} + +func TestOneWordReason(t *testing.T) { + r := &nethttp.Response{Status: "200 FOO"} + if GetReason(r) != "FOO" { + t.Errorf("Unexpected reason found") + } +} + +func TestMultiWordReason(t *testing.T) { + r := &nethttp.Response{Status: "200 FOO BAR BAZ"} + if GetReason(r) != "FOO BAR BAZ" { + t.Errorf("Unexpected reason found") + } +} + +func TestOddSizeStatusCode(t *testing.T) { + r := &nethttp.Response{Status: "2 FOO BAR BAZ"} + if GetReason(r) != "FOO BAR BAZ" { + t.Errorf("Unexpected reason found") + } +}