websocket兼容完成

This commit is contained in:
Liujian
2022-10-27 17:54:20 +08:00
parent 487e1f8943
commit da12a11f8b
16 changed files with 712 additions and 766 deletions

View File

@@ -2,21 +2,48 @@ package http_context
import (
"errors"
"fmt"
"io"
"sync"
"github.com/eolinker/eosc/log"
"github.com/eolinker/eosc/utils/config"
http_context "github.com/eolinker/eosc/eocontext/http-context"
http_service "github.com/eolinker/eosc/eocontext/http-context"
"github.com/fasthttp/websocket"
)
var _ http_context.IWebsocketContext = (*WebsocketContext)(nil)
type WebsocketContext struct {
*Context
clientConn *websocket.Conn
*HttpContext
upstreamConn *websocket.Conn
}
var upgrader = websocket.FastHTTPUpgrader{}
func (w *WebsocketContext) Upgrade() error {
return nil
err := upgrader.Upgrade(w.fastHttpRequestCtx, func(conn *websocket.Conn) {
defer conn.Close()
defer w.upstreamConn.Close()
wg := &sync.WaitGroup{}
wg.Add(2)
go func() {
size, err := io.Copy(conn.UnderlyingConn(), w.upstreamConn.UnderlyingConn())
log.Infof("finish copy upstream: size is %d,err is %v", size, err)
wg.Done()
}()
go func() {
size, err := io.Copy(w.upstreamConn.UnderlyingConn(), conn.UnderlyingConn())
log.Infof("finish copy upstream: size is %d,err is %v", size, err)
wg.Done()
}()
wg.Wait()
})
return err
}
func (w *WebsocketContext) IsWebsocket() bool {
@@ -24,21 +51,25 @@ func (w *WebsocketContext) IsWebsocket() bool {
}
func NewWebsocketContext(ctx http_context.IHttpContext) (*WebsocketContext, error) {
httpCtx, ok := ctx.(*Context)
httpCtx, ok := ctx.(*HttpContext)
if !ok {
return nil, errors.New("unsupported context type")
}
return &WebsocketContext{Context: httpCtx}, nil
}
func (w *WebsocketContext) GetClientConn() *websocket.Conn {
return w.clientConn
}
func (w *WebsocketContext) GetUpstreamConn() *websocket.Conn {
return w.upstreamConn
return &WebsocketContext{HttpContext: httpCtx}, nil
}
func (w *WebsocketContext) SetUpstreamConn(conn *websocket.Conn) {
w.upstreamConn = conn
}
func (w *WebsocketContext) Assert(i interface{}) error {
if v, ok := i.(*http_context.IWebsocketContext); ok {
*v = w
return nil
}
if v, ok := i.(*http_service.IHttpContext); ok {
*v = w
return nil
}
return fmt.Errorf("not suport:%s", config.TypeNameOf(i))
}