relay.go 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package controller
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "io"
  6. "net/http"
  7. "one-api/common"
  8. )
  9. func Relay(c *gin.Context) {
  10. channelType := c.GetInt("channel")
  11. host := common.ChannelHosts[channelType]
  12. req, err := http.NewRequest(c.Request.Method, fmt.Sprintf("%s/%s", host, c.Request.URL.String()), c.Request.Body)
  13. if err != nil {
  14. c.JSON(http.StatusOK, gin.H{
  15. "error": gin.H{
  16. "message": err.Error(),
  17. "type": "one_api_error",
  18. },
  19. })
  20. return
  21. }
  22. req.Header = c.Request.Header.Clone()
  23. client := &http.Client{}
  24. resp, err := client.Do(req)
  25. if err != nil {
  26. c.JSON(http.StatusOK, gin.H{
  27. "error": gin.H{
  28. "message": err.Error(),
  29. "type": "one_api_error",
  30. },
  31. })
  32. return
  33. }
  34. for k, v := range resp.Header {
  35. c.Writer.Header().Set(k, v[0])
  36. }
  37. _, err = io.Copy(c.Writer, resp.Body)
  38. //body, err := io.ReadAll(resp.Body)
  39. //_, err = c.Writer.Write(body)
  40. if err != nil {
  41. c.JSON(http.StatusOK, gin.H{
  42. "error": gin.H{
  43. "message": err.Error(),
  44. "type": "one_api_error",
  45. },
  46. })
  47. return
  48. }
  49. }