opencode-cursor-agent/internal/handler/chat/chat_completions_handler.go

56 lines
1.5 KiB
Go

// Code scaffolded by goctl. Safe to edit.
// goctl 1.10.1
package chat
import (
"encoding/json"
"io"
"net/http"
"cursor-api-proxy/internal/logic/chat"
"cursor-api-proxy/internal/svc"
"cursor-api-proxy/internal/types"
"cursor-api-proxy/pkg/infrastructure/httputil"
)
func ChatCompletionsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Read raw body first
rawBody, err := io.ReadAll(r.Body)
if err != nil {
httputil.WriteJSON(w, 400, map[string]interface{}{
"error": map[string]string{"message": "failed to read body", "code": "bad_request"},
}, nil)
return
}
var req types.ChatCompletionRequest
if err := json.Unmarshal(rawBody, &req); err != nil {
httputil.WriteJSON(w, 400, map[string]interface{}{
"error": map[string]string{"message": "invalid JSON body", "code": "bad_request"},
}, nil)
return
}
l := chat.NewChatCompletionsLogic(r.Context(), svcCtx)
if req.Stream {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("Connection", "keep-alive")
w.Header().Set("X-Accel-Buffering", "no")
_ = l.ChatCompletionsStream(&req, w, r.Method, r.URL.Path)
} else {
resp, err := l.ChatCompletions(&req)
if err != nil {
httputil.WriteJSON(w, 500, map[string]interface{}{
"error": map[string]string{"message": err.Error(), "code": "internal_error"},
}, nil)
} else {
httputil.WriteJSON(w, 200, resp, nil)
}
}
}
}