chat_completions_handler.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package chat
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. "github.com/zeromicro/go-zero/rest/httpx"
  8. "wechat-api/internal/logic/chat"
  9. "wechat-api/internal/svc"
  10. "wechat-api/internal/types"
  11. "github.com/zeromicro/go-zero/core/logx"
  12. )
  13. // swagger:route post /v1/chat/completions chat ChatCompletions
  14. //
  15. //
  16. //
  17. // Parameters:
  18. // + name: body
  19. // require: true
  20. // in: body
  21. // type: CompApiReq
  22. //
  23. // Responses:
  24. // 200: CompOpenApiResp
  25. func ChatCompletionsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
  26. return func(w http.ResponseWriter, r *http.Request) {
  27. var req types.CompApiReq
  28. /*
  29. if err := httpx.Parse(r, &req, true); err != nil {
  30. httpx.ErrorCtx(r.Context(), w, err)
  31. return
  32. }
  33. */
  34. // 读取请求体
  35. body, err := io.ReadAll(r.Body)
  36. if err != nil {
  37. httpx.ErrorCtx(r.Context(), w, err)
  38. return
  39. }
  40. // 将请求体还原,以便后续处理
  41. r.Body = io.NopCloser(bytes.NewBuffer(body))
  42. logx.Info(string(body))
  43. err = json.Unmarshal([]byte(string(body)), &req)
  44. if err != nil {
  45. httpx.ErrorCtx(r.Context(), w, err)
  46. return
  47. }
  48. // 打印请求体
  49. logx.Info(req)
  50. l := chat.NewChatCompletionsLogic(r.Context(), svcCtx)
  51. am, resp, err := l.ChatCompletions(&req)
  52. if err != nil {
  53. httpx.ErrorCtx(r.Context(), w, err)
  54. } else {
  55. if !am {
  56. httpx.OkJsonCtx(r.Context(), w, resp)
  57. } else {
  58. httpx.OkJsonCtx(r.Context(), w, types.BaseDataInfo{Code: 0, Msg: "请求已经受理"})
  59. }
  60. }
  61. }
  62. }