refactor: move functions to render package

This commit is contained in:
JustSong
2024-06-30 18:26:47 +08:00
parent 1923ded809
commit 616759933a
15 changed files with 70 additions and 51 deletions

25
common/render/render.go Normal file
View File

@@ -0,0 +1,25 @@
package render
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/songquanpeng/one-api/common"
)
func StringData(c *gin.Context, str string) {
c.Render(-1, common.CustomEvent{Data: "data: " + str})
}
func ObjectData(c *gin.Context, object interface{}) error {
jsonData, err := json.Marshal(object)
if err != nil {
return fmt.Errorf("error marshalling object: %w", err)
}
StringData(c, string(jsonData))
return nil
}
func Done(c *gin.Context) {
StringData(c, "[DONE]")
}

View File

@@ -1,11 +1,7 @@
package common
import (
"encoding/json"
"fmt"
"strings"
"github.com/gin-gonic/gin"
"github.com/songquanpeng/one-api/common/config"
)
@@ -16,18 +12,3 @@ func LogQuota(quota int64) string {
return fmt.Sprintf("%d 点额度", quota)
}
}
func RenderStringData(c *gin.Context, data string) {
data = strings.TrimPrefix(data, "data: ")
c.Render(-1, CustomEvent{Data: "data: " + strings.TrimSuffix(data, "\r")})
c.Writer.Flush()
}
func RenderData(c *gin.Context, response interface{}) error {
jsonResponse, err := json.Marshal(response)
if err != nil {
return fmt.Errorf("error marshalling stream response: %w", err)
}
RenderStringData(c, string(jsonResponse))
return nil
}