Skip to content

Commit

Permalink
Enhance ProcessGuard function to accept optional CORS handlers; impro…
Browse files Browse the repository at this point in the history
…ve error handling by invoking CORS middleware on errors and returning structured JSON responses. This change streamlines error reporting and enhances flexibility in handling cross-origin requests.
  • Loading branch information
trheyi committed Dec 14, 2024
1 parent e5ae01f commit 8dec253
Showing 1 changed file with 9 additions and 2 deletions.
11 changes: 9 additions & 2 deletions api/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ var HTTPGuards = map[string]gin.HandlerFunc{}
var registeredOptions = map[string]bool{}

// ProcessGuard guard process
func ProcessGuard(name string) gin.HandlerFunc {
func ProcessGuard(name string, cors ...gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
var body interface{}
if c.Request.Body != nil {
Expand Down Expand Up @@ -56,7 +56,11 @@ func ProcessGuard(name string) gin.HandlerFunc {

process, err := process.Of(name, args...)
if err != nil {
c.JSON(500, gin.H{"code": 500, "message": "Guard process error: " + err.Error()})
if len(cors) > 0 {
cors[0](c)
}
ex := exception.New(err.Error(), 500)
c.JSON(ex.Code, gin.H{"code": ex.Code, "message": ex.Message})
c.Abort()
return
}
Expand All @@ -76,6 +80,9 @@ func ProcessGuard(name string) gin.HandlerFunc {
err = process.Execute()
if err != nil {
ex := exception.New(err.Error(), 500)
if len(cors) > 0 {
cors[0](c)
}
c.JSON(ex.Code, gin.H{"code": ex.Code, "message": ex.Message})
c.Abort()
return
Expand Down

0 comments on commit 8dec253

Please sign in to comment.