2026-04-03 09:15:35 +00:00
|
|
|
// Code scaffolded by goctl. Safe to edit.
|
|
|
|
|
// goctl 1.10.1
|
|
|
|
|
|
|
|
|
|
package chat
|
|
|
|
|
|
|
|
|
|
import (
|
2026-04-04 04:49:32 +00:00
|
|
|
"encoding/json"
|
|
|
|
|
"io"
|
2026-04-03 09:15:35 +00:00
|
|
|
"net/http"
|
|
|
|
|
|
|
|
|
|
"cursor-api-proxy/internal/logic/chat"
|
|
|
|
|
"cursor-api-proxy/internal/svc"
|
|
|
|
|
"cursor-api-proxy/internal/types"
|
2026-04-03 15:17:04 +00:00
|
|
|
|
2026-04-04 04:49:32 +00:00
|
|
|
"cursor-api-proxy/pkg/infrastructure/httputil"
|
2026-04-03 09:15:35 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func AnthropicMessagesHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
|
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
2026-04-04 04:49:32 +00:00
|
|
|
// Read raw body first
|
|
|
|
|
rawBody, err := io.ReadAll(r.Body)
|
|
|
|
|
if err != nil {
|
|
|
|
|
httputil.WriteJSON(w, 400, map[string]interface{}{
|
|
|
|
|
"error": map[string]string{"type": "invalid_request_error", "message": "failed to read body"},
|
|
|
|
|
}, nil)
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-03 09:15:35 +00:00
|
|
|
var req types.AnthropicRequest
|
2026-04-04 04:49:32 +00:00
|
|
|
if err := json.Unmarshal(rawBody, &req); err != nil {
|
|
|
|
|
httputil.WriteJSON(w, 400, map[string]interface{}{
|
|
|
|
|
"error": map[string]string{"type": "invalid_request_error", "message": "invalid JSON body"},
|
|
|
|
|
}, nil)
|
2026-04-03 09:15:35 +00:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
l := chat.NewAnthropicMessagesLogic(r.Context(), svcCtx)
|
2026-04-03 15:17:04 +00:00
|
|
|
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.AnthropicMessagesStream(&req, w, r.Method, r.URL.Path)
|
2026-04-03 09:15:35 +00:00
|
|
|
} else {
|
2026-04-03 15:17:04 +00:00
|
|
|
err := l.AnthropicMessages(&req, w, r.Method, r.URL.Path)
|
|
|
|
|
if err != nil {
|
2026-04-04 04:49:32 +00:00
|
|
|
httputil.WriteJSON(w, 500, map[string]interface{}{
|
|
|
|
|
"error": map[string]string{"type": "api_error", "message": err.Error()},
|
|
|
|
|
}, nil)
|
2026-04-03 15:17:04 +00:00
|
|
|
}
|
2026-04-03 09:15:35 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|