Esempio n. 1
0
// Run() implements the rack.Middleware interface
func (this Controller) Run(vars map[string]interface{}, next func()) {
	r := (httper.V)(vars).GetRequest()
	if strings.ToLower(r.Header.Get("Upgrade")) != "websocket" {
		//if it wasn't a websocket request, ignore it
		next()
	} else {
		var handler websocket.Handler = func(ws *websocket.Conn) {
			vars[websocketIndex] = ws
			this.onOpen.Run(vars, func() {})
			defer func() {
				this.onClose.Run(vars, func() {})
				ws.Close()
			}()
			for {
				//Message Loop

				//Get the message from the client
				message := this.onStorage()
				err := this.messageType.Receive(ws, message)

				//If there are no messages, we're done here
				if err != nil {
					if err != io.EOF {
						(logger.V)(vars).Println(err)
						continue
					} else {
						break
					}
				}

				//respond to the message in a goroutine
				go func() {
					vars[messageIndex] = reflect.Indirect(reflect.ValueOf(message)).Interface()
					this.onMessage.Run(vars, func() {})

					//If we have a response, send it back
					response := vars[responseIndex]
					delete(vars, responseIndex)

					if response != nil {
						this.messageType.Send(ws, response)
					}
				}()
			}
		}
		w := (httper.V)(vars).BlankResponse()
		handler.ServeHTTP(w, r)
		w.Save()
	}
}
Esempio n. 2
0
func upgradeWebsocketHandler(wsHandler websocket.Handler) interface{} {
	return func(ctx *web.Context) {
		wsHandler.ServeHTTP(ctx.ResponseWriter, ctx.Request)
	}
}