new-api/service/relay.go

47 lines
1.1 KiB
Go
Raw Normal View History

2024-02-29 01:08:18 +08:00
package service
2024-07-05 20:00:52 +08:00
import (
"encoding/json"
2024-07-17 16:38:56 +08:00
"errors"
2024-07-05 20:00:52 +08:00
"fmt"
"github.com/gin-gonic/gin"
"one-api/common"
)
2024-02-29 01:08:18 +08:00
func SetEventStreamHeaders(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")
c.Writer.Header().Set("Transfer-Encoding", "chunked")
c.Writer.Header().Set("X-Accel-Buffering", "no")
}
2024-07-05 20:00:52 +08:00
2024-07-17 16:38:56 +08:00
func StringData(c *gin.Context, str string) error {
//str = strings.TrimPrefix(str, "data: ")
//str = strings.TrimSuffix(str, "\r")
2024-07-05 20:00:52 +08:00
c.Render(-1, common.CustomEvent{Data: "data: " + str})
2024-07-17 16:38:56 +08:00
if c.Writer != nil {
c.Writer.Flush()
} else {
return errors.New("writer is nil")
}
return nil
2024-07-05 20:00:52 +08:00
}
func ObjectData(c *gin.Context, object interface{}) error {
jsonData, err := json.Marshal(object)
if err != nil {
return fmt.Errorf("error marshalling object: %w", err)
}
2024-07-17 16:38:56 +08:00
return StringData(c, string(jsonData))
2024-07-05 20:00:52 +08:00
}
func Done(c *gin.Context) {
2024-07-17 16:38:56 +08:00
_ = StringData(c, "[DONE]")
2024-07-05 20:00:52 +08:00
}
2024-07-13 19:55:22 +08:00
func GetResponseID(c *gin.Context) string {
logID := c.GetString("X-Oneapi-Request-Id")
return fmt.Sprintf("chatcmpl-%s", logID)
}