support event stream
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"reflect"
|
||||
|
||||
@@ -80,6 +81,75 @@ func PrintDataErrorResult(c *core.WebContext, contentType string, err *errs.Erro
|
||||
c.Abort()
|
||||
}
|
||||
|
||||
// SetEventStreamHeader sets the headers for event stream response
|
||||
func SetEventStreamHeader(c *core.WebContext) {
|
||||
c.Writer.Header().Set("Content-Type", "text/event-stream")
|
||||
c.Writer.Header().Set("Cache-Control", "no-cache")
|
||||
c.Writer.Header().Set("Connection", "keep-alive")
|
||||
}
|
||||
|
||||
func WriteEventStreamJsonSuccessResult(c *core.WebContext, result any) {
|
||||
data, err := json.Marshal(result)
|
||||
|
||||
if err != nil {
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
_, err = c.Writer.WriteString("data: " + string(data) + "\n\n")
|
||||
|
||||
if err != nil {
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Writer.Flush()
|
||||
}
|
||||
|
||||
func WriteEventStreamJsonErrorResult(c *core.WebContext, originalErr *errs.Error) {
|
||||
c.SetResponseError(originalErr)
|
||||
|
||||
errorMessage := originalErr.Error()
|
||||
|
||||
if originalErr.Code() == errs.ErrIncompleteOrIncorrectSubmission.Code() && len(originalErr.BaseError) > 0 {
|
||||
validationErrors, ok := originalErr.BaseError[0].(validator.ValidationErrors)
|
||||
|
||||
if ok {
|
||||
for _, err := range validationErrors {
|
||||
errorMessage = getValidationErrorText(err)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result := gin.H{
|
||||
"success": false,
|
||||
"errorCode": originalErr.Code(),
|
||||
"errorMessage": errorMessage,
|
||||
"path": c.Request.URL.Path,
|
||||
}
|
||||
|
||||
if originalErr.Context != nil {
|
||||
result["context"] = originalErr.Context
|
||||
}
|
||||
|
||||
data, err := json.Marshal(result)
|
||||
|
||||
if err != nil {
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
_, err = c.Writer.WriteString("data: " + string(data) + "\n\n")
|
||||
|
||||
if err != nil {
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Writer.Flush()
|
||||
}
|
||||
|
||||
func getValidationErrorText(err validator.FieldError) string {
|
||||
fieldName := GetFirstLowerCharString(err.Field())
|
||||
|
||||
|
||||
Reference in New Issue
Block a user