MCPcopy
hub / github.com/QuantumNous/new-api / doRequest

Function doRequest

relay/channel/api_request.go:487–533  ·  view source on GitHub ↗
(c *gin.Context, req *http.Request, info *common.RelayInfo)

Source from the content-addressed store, hash-verified

485 return doRequest(c, req, info)
486}
487func doRequest(c *gin.Context, req *http.Request, info *common.RelayInfo) (*http.Response, error) {
488 var client *http.Client
489 var err error
490 if info.ChannelSetting.Proxy != "" {
491 client, err = service.NewProxyHttpClient(info.ChannelSetting.Proxy)
492 if err != nil {
493 return nil, fmt.Errorf("new proxy http client failed: %w", err)
494 }
495 } else {
496 client = service.GetHttpClient()
497 }
498
499 var stopPinger context.CancelFunc
500 if info.IsStream {
501 helper.SetEventStreamHeaders(c)
502 // 处理流式请求的 ping 保活
503 generalSettings := operation_setting.GetGeneralSetting()
504 if generalSettings.PingIntervalEnabled && !info.DisablePing {
505 pingInterval := time.Duration(generalSettings.PingIntervalSeconds) * time.Second
506 stopPinger = startPingKeepAlive(c, pingInterval)
507 // 使用defer确保在任何情况下都能停止ping goroutine
508 defer func() {
509 if stopPinger != nil {
510 stopPinger()
511 logger.LogDebug(c, "SSE ping goroutine stopped by defer")
512 }
513 }()
514 }
515 }
516
517 resp, err := client.Do(req)
518 if err != nil {
519 logger.LogError(c, "do request failed: "+err.Error())
520 return nil, types.NewError(err, types.ErrorCodeDoRequestFailed, types.ErrOptionWithHideErrMsg("upstream error: do request failed"))
521 }
522 if resp == nil {
523 return nil, errors.New("resp is nil")
524 }
525
526 if upID := resp.Header.Get(common2.RequestIdKey); upID != "" {
527 c.Set(common2.UpstreamRequestIdKey, upID)
528 }
529
530 _ = req.Body.Close()
531 _ = c.Request.Body.Close()
532 return resp, nil
533}
534
535func DoTaskApiRequest(a TaskAdaptor, c *gin.Context, info *common.RelayInfo, requestBody io.Reader) (*http.Response, error) {
536 fullRequestURL, err := a.BuildRequestURL(info)

Callers 4

DoApiRequestFunction · 0.70
DoFormRequestFunction · 0.70
DoRequestFunction · 0.70
DoTaskApiRequestFunction · 0.70

Calls 14

NewProxyHttpClientFunction · 0.92
GetHttpClientFunction · 0.92
SetEventStreamHeadersFunction · 0.92
GetGeneralSettingFunction · 0.92
LogDebugFunction · 0.92
LogErrorFunction · 0.92
NewErrorFunction · 0.92
ErrOptionWithHideErrMsgFunction · 0.92
startPingKeepAliveFunction · 0.85
SetMethod · 0.80
DoMethod · 0.65
ErrorMethod · 0.45

Tested by

no test coverage detected