In the previous article we started learning how to create RESTful API using golang's gin framework. In this article we are going to see how to create a GET
endpoint using golang's gin http framework.
Step 1
Create a file controller.go
in a directory with the name content
in the project.
Create an endpoint in a controller which can accept query parameters and register it for a GET
request in the main.go
file.
package content
import (
"fmt"
"net/http"
"github.com/gin-gonic/gin"
)
func GetContents(ctx *gin.Context) {
name, present := ctx.GetQuery("name")
if !present {
ctx.Error(fmt.Errorf("name is required"))
ctx.AbortWithStatus(http.StatusBadRequest)
return
}
response := make(map[string]string, 0)
response["name"] = name
ctx.JSON(http.StatusOK, response)
}
Step 2
Register the above created endpoint to gin server in the main.go
file. Similar to what we did in Step 4 of previous article add the below code after the http.Server
object creation in the main.go
file.
//gin has the option to group endpoints as shown below
v1 := engine.Group("/api/v1")
{
v1.GET("/contents", content.GetContents)
}
Step 3
Now run the main.go
file.
Access the endpoint localhost:8080/api/v1/contents?name=deepak
and you should get a 200
status with response body
{
"name": "deepak"
}
Now, access the endpoint without the query parameter i.e., localhost:8080/api/v1/contents
and you should get a 400
status with no response body
Step 4
Now let us write some tests to test the above created endpoint. Create a file with the name content_test.go
in the content
directory.
package content
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestGetContents_success(t *testing.T) {
responseRecorder := httptest.NewRecorder()
ctx, engine := gin.CreateTestContext(responseRecorder)
engine.GET("/contents", GetContents)
ctx.Request = httptest.NewRequest(http.MethodGet, "/contents?name=deepak", nil)
engine.ServeHTTP(responseRecorder, ctx.Request)
assert.Equal(t, http.StatusOK, responseRecorder.Code)
expectedBody := map[string]string{
"name": "deepak",
}
var actualBody map[string]string
err := json.Unmarshal(responseRecorder.Body.Bytes(), &actualBody)
if err != nil {
t.FailNow()
}
assert.Equal(t, expectedBody, actualBody)
}
func TestGetContents_failure(t *testing.T) {
responseRecorder := httptest.NewRecorder()
ctx, engine := gin.CreateTestContext(responseRecorder)
engine.GET("/contents", GetContents)
ctx.Request = httptest.NewRequest(http.MethodGet, "/contents", nil)
engine.ServeHTTP(responseRecorder, ctx.Request)
assert.Equal(t, http.StatusBadRequest, responseRecorder.Code)
}
Did you find this article valuable?
Support Deepak by becoming a sponsor. Any amount is appreciated!