Skip to content

Commit

Permalink
feat: handling content types in gin server
Browse files Browse the repository at this point in the history
  • Loading branch information
RawanMostafa08 committed Sep 18, 2024
1 parent 39a0584 commit 7a9d988
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 7 deletions.
11 changes: 10 additions & 1 deletion pkg/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
32 changes: 26 additions & 6 deletions pkg/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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)
}
Expand All @@ -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)

})
Expand Down

0 comments on commit 7a9d988

Please sign in to comment.