This commit is contained in:
2025-08-13 13:58:55 +07:00
parent 26765fcc51
commit 71fd910b29
8 changed files with 106 additions and 9 deletions

View File

@@ -0,0 +1,55 @@
package middleware
import (
"net/http"
"template_blueprint/pkg/models"
"github.com/gin-gonic/gin"
)
// ErrorHandler handles errors globally
func ErrorHandler() gin.HandlerFunc {
return func(c *gin.Context) {
c.Next()
if len(c.Errors) > 0 {
err := c.Errors.Last()
status := http.StatusInternalServerError
// Determine status code based on error type
switch err.Type {
case gin.ErrorTypeBind:
status = http.StatusBadRequest
case gin.ErrorTypeRender:
status = http.StatusUnprocessableEntity
case gin.ErrorTypePrivate:
status = http.StatusInternalServerError
}
response := models.ErrorResponse{
Error: "internal_error",
Message: err.Error(),
Code: status,
}
c.JSON(status, response)
}
}
}
// CORS middleware configuration
func CORSConfig() gin.HandlerFunc {
return gin.HandlerFunc(func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, PATCH")
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
})
}

View File

@@ -7,6 +7,9 @@ import (
"github.com/gin-gonic/gin"
swaggerFiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
patientHandler "template_blueprint/pkg/handlers/patient"
datapoliklinikHandler "template_blueprint/pkg/handlers/poliklinik"
dataRetribusi "template_blueprint/pkg/handlers/retribusi"
//_ "template_blueprint/docs"
//swaggerFiles "github.com/swaggo/files"
@@ -16,11 +19,7 @@ import (
"net/http"
//_ "template_blueprint/cmd/api/docs"
"template_blueprint/cmd/web"
//_ "template_blueprint/internal/docs"
_ "template_blueprint/docs"
patientHandler "template_blueprint/pkg/handlers/patient"
datapoliklinikHandler "template_blueprint/pkg/handlers/poliklinik"
dataRetribusi "template_blueprint/pkg/handlers/retribusi"
"time"
)
@@ -32,7 +31,8 @@ func (s *Server) RegisterRoutes() http.Handler {
AllowHeaders: []string{"Origin", "Content-Type"},
AllowCredentials: true,
}))
//r.Use(middleware.CORSConfig())
//r.Use(middleware.ErrorHandler())
//r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
r.GET("/", s.HelloWorldHandler)