context_builder.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package hooks
  2. import (
  3. "net/http"
  4. "github.com/QuantumNous/new-api/common"
  5. "github.com/QuantumNous/new-api/constant"
  6. "github.com/QuantumNous/new-api/core/interfaces"
  7. "github.com/gin-gonic/gin"
  8. )
  9. // BuildHookContext 从Gin Context构建HookContext
  10. func BuildHookContext(c *gin.Context) *interfaces.HookContext {
  11. ctx := &interfaces.HookContext{
  12. GinContext: c,
  13. Request: c.Request,
  14. Data: make(map[string]interface{}),
  15. }
  16. // 提取Channel信息
  17. if channelID, ok := common.GetContextKey(c, constant.ContextKeyChannelId); ok {
  18. if id, ok := channelID.(int); ok {
  19. ctx.ChannelID = id
  20. }
  21. }
  22. if channelType, ok := common.GetContextKey(c, constant.ContextKeyChannelType); ok {
  23. if t, ok := channelType.(int); ok {
  24. ctx.ChannelType = t
  25. }
  26. }
  27. if channelName, ok := common.GetContextKey(c, constant.ContextKeyChannelName); ok {
  28. if name, ok := channelName.(string); ok {
  29. ctx.ChannelName = name
  30. }
  31. }
  32. // 提取Model信息
  33. if originalModel, ok := common.GetContextKey(c, constant.ContextKeyOriginalModel); ok {
  34. if m, ok := originalModel.(string); ok {
  35. ctx.OriginalModel = m
  36. ctx.Model = m // 使用OriginalModel作为Model
  37. }
  38. }
  39. // 提取User信息
  40. if userID, ok := common.GetContextKey(c, constant.ContextKeyUserId); ok {
  41. if id, ok := userID.(int); ok {
  42. ctx.UserID = id
  43. }
  44. }
  45. if tokenID, ok := common.GetContextKey(c, constant.ContextKeyTokenId); ok {
  46. if id, ok := tokenID.(int); ok {
  47. ctx.TokenID = id
  48. }
  49. }
  50. if group, ok := common.GetContextKey(c, constant.ContextKeyUsingGroup); ok {
  51. if g, ok := group.(string); ok {
  52. ctx.Group = g
  53. }
  54. }
  55. return ctx
  56. }
  57. // UpdateHookContextWithResponse 更新HookContext的Response信息
  58. func UpdateHookContextWithResponse(ctx *interfaces.HookContext, resp *http.Response, body []byte) {
  59. ctx.Response = resp
  60. ctx.ResponseBody = body
  61. }
  62. // UpdateHookContextWithRequest 更新HookContext的Request信息
  63. func UpdateHookContextWithRequest(ctx *interfaces.HookContext, body []byte) {
  64. ctx.RequestBody = body
  65. }