From 7a9d988a018c22c1ccf83476e133297ec72c173f Mon Sep 17 00:00:00 2001 From: RawanMostafa08 Date: Wed, 18 Sep 2024 15:47:34 +0300 Subject: [PATCH] feat: handling content types in gin server --- pkg/handlers.go | 11 ++++++++++- pkg/handlers_test.go | 32 ++++++++++++++++++++++++++------ 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/pkg/handlers.go b/pkg/handlers.go index 4c107f6..f5497b5 100644 --- a/pkg/handlers.go +++ b/pkg/handlers.go @@ -57,7 +57,16 @@ func GinHandler(c *gin.Context) { } currentTime := time.Now() trucatedTime := truncateToSec(currentTime) - c.String(http.StatusOK, trucatedTime.String()) + + if strings.Contains(c.Request.Header.Get("content-type"), "text/plain") { + c.Writer.Header().Set("Content-Type", "text/plain") + c.String(http.StatusOK, trucatedTime.String()) + + } else if strings.Contains(c.Request.Header.Get("content-type"), "json") { + + c.JSON(http.StatusOK, trucatedTime) + } + } func GinHome(c *gin.Context) { diff --git a/pkg/handlers_test.go b/pkg/handlers_test.go index 0befa98..fd15375 100644 --- a/pkg/handlers_test.go +++ b/pkg/handlers_test.go @@ -123,19 +123,34 @@ func TestGinHome(t *testing.T) { func TestGinHandler(t *testing.T) { + truncatedTime := truncateToSec(time.Now()) + timeJson, err := json.Marshal(truncatedTime) + if err != nil { + t.Errorf("error converting to json: %v", err) + } testcases := []struct { testcaseName string method string url string statusCode int - expected string + expected any + contentType string }{ { - testcaseName: "correct method and url", + testcaseName: "correct method and url, plain text type", + method: "GET", + url: "/datetime", + statusCode: 200, + expected: truncatedTime.String(), + contentType: "text/plain", + }, + { + testcaseName: "correct method and url, json type", method: "GET", url: "/datetime", statusCode: 200, - expected: truncateToSec(time.Now()).String(), + expected: timeJson, + contentType: "application/json", }, { testcaseName: "wrong method", @@ -150,15 +165,16 @@ func TestGinHandler(t *testing.T) { t.Run(testcase.testcaseName, func(t *testing.T) { r := gin.Default() - if testcase.method == "GET" { + if testcase.method == "GET" { r.GET(testcase.url, GinHandler) } else { r.POST(testcase.url, GinHandler) - } req, err := http.NewRequest(testcase.method, testcase.url, nil) + req.Header.Add("content-type", testcase.contentType) + if err != nil { t.Errorf("Error in new request %v", err) } @@ -169,7 +185,11 @@ func TestGinHandler(t *testing.T) { if err != nil { t.Errorf("Error reading response body %v", err) } - assertEquality(t, testcase.expected, string(resBody)) + if testcase.contentType == "application/json" { + assertEquality(t, testcase.expected, resBody) + } else { + assertEquality(t, testcase.expected, string(resBody)) + } assertEquality(t, testcase.statusCode, res.Code) })