mirror of
https://github.com/songquanpeng/one-api.git
synced 2025-11-21 07:26:47 +08:00
refactor: move functions to render package
This commit is contained in:
25
common/render/render.go
Normal file
25
common/render/render.go
Normal 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]")
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user