@@ -187,34 +187,64 @@ type sseClaudeResponseWriter struct {
187187}
188188
189189func  (w  * sseResponseWriter ) Write (data  []byte ) (int , error ) {
190+ 	// 如果是 SSE 的请求 
190191	if  strings .Contains (w .Header ().Get ("Content-Type" ), "text/event-stream" ) {
191192		reader  :=  bufio .NewReader (bytes .NewReader (data ))
193+ 
194+ 		var  totalBytesWritten  int 
192195		for  {
196+ 			// 逐行读取数据 
193197			line , err  :=  reader .ReadString ('\n' )
194198			if  err  !=  nil  {
195199				if  err  ==  io .EOF  {
196200					break 
197201				}
198- 				return  0 , err 
202+ 				return  totalBytesWritten , err 
199203			}
204+ 
205+ 			// 如果是 SSE 格式的 "data: " 行,进行处理 
200206			if  strings .HasPrefix (line , "data: " ) {
201207				jsonData  :=  strings .TrimPrefix (line , "data: " )
202208				var  event  map [string ]interface {}
203209				if  err  :=  json .Unmarshal ([]byte (jsonData ), & event ); err  ==  nil  {
210+ 					// 提取并处理消息内容 
204211					if  message , ok  :=  event ["message" ].(map [string ]interface {}); ok  {
205212						if  content , ok  :=  message ["content" ].(map [string ]interface {}); ok  {
206213							if  parts , ok  :=  content ["parts" ].([]interface {}); ok  &&  len (parts ) >  0  {
207214								if  text , ok  :=  parts [0 ].(string ); ok  {
215+ 									// 更新 messages 字段 
208216									w .messages  =  text 
209- 									w .model  =  message ["metadata" ].(map [string ]interface {})["model_slug" ].(string )
217+ 
218+ 									// 检查 model_slug 并更新 model 字段 
219+ 									if  metadata , ok  :=  message ["metadata" ].(map [string ]interface {}); ok  {
220+ 										if  model , ok  :=  metadata ["model_slug" ].(string ); ok  {
221+ 											w .model  =  model 
222+ 										}
223+ 									}
224+ 									if  w .model  ==  ""  {
225+ 										w .model  =  "UNKNOWN" 
226+ 									}
210227								}
211228							}
212229						}
213230					}
214231				}
215232			}
233+ 
234+ 			// 将当前行写入到原始的 ResponseWriter 中,保持流式输出 
235+ 			bytesWritten , err  :=  w .ResponseWriter .Write ([]byte (line ))
236+ 			if  err  !=  nil  {
237+ 				return  totalBytesWritten , err 
238+ 			}
239+ 			totalBytesWritten  +=  bytesWritten 
240+ 
241+ 			// 刷新输出,确保数据立即发送到客户端 
242+ 			w .ResponseWriter .Flush ()
216243		}
244+ 		return  totalBytesWritten , nil 
217245	}
246+ 
247+ 	// 对于非 SSE 请求,直接写入数据 
218248	return  w .ResponseWriter .Write (data )
219249}
220250
0 commit comments