package nnet import ( "fmt" "git.noahlan.cn/noahlan/nnet/config" "git.noahlan.cn/noahlan/ntool/nlog" "github.com/gorilla/websocket" "net/http" "os" "strings" ) type WsServerOption func(conf config.WSServerFullConf) func WithWSCheckOrigin(fn func(*http.Request) bool) WsServerOption { return func(conf config.WSServerFullConf) { conf.CheckOrigin = fn } } // ListenWebsocket 开始监听Websocket func (ngin *Engine) ListenWebsocket(conf config.WSServerFullConf, serverOpts []WsServerOption, evtOpts ...WsEventOption) error { for _, opt := range serverOpts { opt(conf) } for _, opt := range evtOpts { opt(conf.WSEvent) } err := ngin.setup() if err != nil { nlog.Errorf("%s failed to setup server, err:%v", ngin.LogPrefix(), err) return err } nlog.Infof("%s now listening websocket at %s.", ngin.LogPrefix(), conf.Addr) ngin.upgradeWebsocket(conf) if conf.IsTLS() { if err := http.ListenAndServeTLS(conf.Addr, conf.TLSCertificate, conf.TLSKey, nil); err != nil { nlog.Errorf("%s failed to listening websocket with TLS at %s %v", ngin.LogPrefix(), conf.Addr, err) return err } } else { if err := http.ListenAndServe(conf.Addr, nil); err != nil { nlog.Errorf("%s failed to listening websocket at %s %v", ngin.LogPrefix(), conf.Addr, err) return err } } return nil } func (ngin *Engine) upgradeWebsocket(conf config.WSServerFullConf) { upgrade := websocket.Upgrader{ HandshakeTimeout: conf.HandshakeTimeout, ReadBufferSize: conf.ReadBufferSize, WriteBufferSize: conf.WriteBufferSize, CheckOrigin: conf.CheckOrigin, EnableCompression: conf.Compression, } path := fmt.Sprintf("/%s", strings.TrimPrefix(conf.Path, "/")) http.HandleFunc(path, func(writer http.ResponseWriter, request *http.Request) { wc, err := upgrade.Upgrade(writer, request, nil) if err != nil { nlog.Errorf("%s Upgrade failure, URI=%ng, Error=%ng", ngin.LogPrefix(), request.RequestURI, err.Error()) return } err = ngin.pool.Submit(func() { _ = ngin.handleWS(wc, conf.WSEvent) }) if err != nil { nlog.Errorf("%s submit conn pool err: %v", ngin.LogPrefix(), err.Error()) os.Exit(1) } }) }