I'm confused as to how to structure my project while using gin. I want it to be TDD-like. I followed the process but now I'm stuck.
I want it to be something like https://quii.gitbook.io/learn-go-with-tests/questions-and-answers/http-handlers-revisited#new-design where my Server struct would have db connection, router, logging configs etc and I can swap them out while testing. I realise this will happen through the usage of interfaces but I'm still confused. I'm posting my code below. Please help. Any other tips adjacent to the topic in question is also hugely appreciated.
main.go
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r = SetupRoutes(r)
r.Run()
}
func SetupRoutes(r *gin.Engine) *gin.Engine {
r.Any("/health", GetHealthStatus)
r.GET("/", GetHomePage)
return r
}
func GetHealthStatus(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"mssg": "OK",
})
}
func GetHomePage(ctx *gin.Context) {
ctx.String(http.StatusOK, "This is the homepage. HTML will be added later")
}
maintest.go
package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func TestServer(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.Default()
router = SetupRoutes(router)
t.Run("test /health route", func(t *testing.T) {
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/health", nil)
router.ServeHTTP(w, r)
assert.Equal(t, w.Code, http.StatusOK)
assert.JSONEq(t, w.Body.String(), `{"mssg": "OK"}`)
})
t.Run("test / route", func(t *testing.T) {
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/", nil)
router.ServeHTTP(w, r)
assert.Equal(t, w.Code, http.StatusOK)
})
}