Skip to content

Commit

Permalink
Refactor WriteResponse method to improve readability and error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
sergi committed Dec 18, 2023
1 parent 1432241 commit 81ea50b
Showing 1 changed file with 8 additions and 15 deletions.
23 changes: 8 additions & 15 deletions evo.context.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@ package evo

import (
"fmt"
"github.com/getevo/evo/v2/lib/generic"
"github.com/getevo/evo/v2/lib/outcome"
"github.com/gofiber/fiber/v2"
"github.com/tidwall/gjson"
"net/url"
"reflect"
"strings"
"time"

"github.com/getevo/evo/v2/lib/generic"
"github.com/getevo/evo/v2/lib/outcome"
"github.com/gofiber/fiber/v2"
"github.com/tidwall/gjson"
)

var errorType = reflect.TypeOf(fmt.Errorf(""))
Expand Down Expand Up @@ -93,6 +94,7 @@ func (r *Request) WriteResponse(resp ...any) {
return
}
var message = false
r.Response.Success = false
for _, item := range resp {
ref := reflect.ValueOf(item)

Expand Down Expand Up @@ -140,7 +142,7 @@ func (r *Request) WriteResponse(resp ...any) {
r.Status(v.StatusCode)
}
if len(v.Cookies) > 0 {
for idx, _ := range v.Cookies {
for idx := range v.Cookies {
r.SetRawCookie(v.Cookies[idx])
}
}
Expand Down Expand Up @@ -170,39 +172,30 @@ func (r *Request) WriteResponse(resp ...any) {

if len(v.Errors) > 0 {
r.Response.Success = false
for _, err := range v.Errors {
r.Response.Error = append(r.Response.Error, err)
}
r.Response.Error = append(r.Response.Error, v.Errors...)
}
} else {
r.Response.Data = item
}

case reflect.Bool:
r.Response.Success = item.(bool)
break
case reflect.Int32, reflect.Int16, reflect.Int64:
r.Response.Data = item.(int)
break
case reflect.String:
if !message {
r.Response.Data = item.(string)
message = true
} else {
r.Response.Data = item
}
break
default:
r.Response.Data = item
r.Response.Success = true
}

}
if r.Response.Data == nil {
r.Response.Success = false
}
r._writeResponse(r.Response)

}

func (r *Request) _writeResponse(resp Response) {
Expand Down

0 comments on commit 81ea50b

Please sign in to comment.