frontend_proxy.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package websubsvc
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/yhat/wsutil"
  6. "net/http/httputil"
  7. "net/url"
  8. )
  9. type FrontendProxy struct {
  10. debugRedirectNotFoundURLhttp *url.URL
  11. debugRedirectNotFoundURLws *url.URL
  12. }
  13. func NewFrontendProxy(proxyURL string) (*FrontendProxy, error) {
  14. rurl, err := url.Parse(proxyURL)
  15. if err != nil {
  16. return nil, fmt.Errorf("invalid proxy url: %w", err)
  17. }
  18. rurl4ws, err := url.Parse(proxyURL)
  19. if err != nil {
  20. return nil, fmt.Errorf("invalid proxy url: %w", err)
  21. }
  22. if rurl4ws.Scheme == "https" {
  23. rurl4ws.Scheme = "wss"
  24. } else {
  25. rurl4ws.Scheme = "ws"
  26. }
  27. return &FrontendProxy{
  28. debugRedirectNotFoundURLhttp: rurl,
  29. debugRedirectNotFoundURLws: rurl4ws,
  30. }, nil
  31. }
  32. func (p *FrontendProxy) RedirectNotFoundHandler(context *gin.Context) {
  33. if context.IsWebsocket() {
  34. if p.debugRedirectNotFoundURLws == nil {
  35. return
  36. }
  37. proxy := wsutil.NewSingleHostReverseProxy(p.debugRedirectNotFoundURLws)
  38. proxy.ServeHTTP(context.Writer, context.Request)
  39. } else {
  40. if p.debugRedirectNotFoundURLhttp == nil {
  41. return
  42. }
  43. proxy := httputil.NewSingleHostReverseProxy(p.debugRedirectNotFoundURLhttp)
  44. proxy.ServeHTTP(context.Writer, context.Request)
  45. }
  46. }