当前位置: 首页>>代码示例>>Golang>>正文


Golang websocket.Upgrade函数代码示例

本文整理汇总了Golang中github.com/gorilla/websocket.Upgrade函数的典型用法代码示例。如果您正苦于以下问题:Golang Upgrade函数的具体用法?Golang Upgrade怎么用?Golang Upgrade使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Upgrade函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: ServeHTTP

func (fl *fakeLoggregator) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fl.receivedRequests = append(fl.receivedRequests, r)
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		Fail("Bad Handshake")
		return
	} else if err != nil {
		Fail("Upgrade Close")
		return
	}
	defer ws.Close()

	r.ParseForm()

	for _, msg := range fl.messages {
		ws.WriteMessage(websocket.BinaryMessage, []byte(msg))
	}
	for {
		_, _, err := ws.ReadMessage()

		if err == nil {
			fl.numKeepAlives++
			continue
		}
		return
	}
}
开发者ID:nkuacac,项目名称:loggregator,代码行数:27,代码来源:proxy_handler_test.go

示例2: socket

func socket(w http.ResponseWriter, r *http.Request) {
	log.Print("connection established")
	if _case == "hang" {
		hang := time.Minute
		log.Printf("hanging for %s\n", hang.String())
		time.Sleep(hang)
	}
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if err != nil {
		log.Print(err)
		return
	}
	defer func() {
		ws.Close()
		log.Print("connection closed")
	}()
	for {
		msgt, msg, err := ws.ReadMessage()
		if err != nil {
			log.Print(err)
			return
		}
		log.Print("rcvd: '" + string(msg) + "'")
		ws.WriteMessage(msgt, msg)
	}
}
开发者ID:Damocs0921,项目名称:SwiftWebSocket,代码行数:26,代码来源:server.go

示例3: wsHandler

func wsHandler(w http.ResponseWriter, r *http.Request) {

	// Websocket handshake.
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		return
	}

	addr := ws.RemoteAddr()

	log.Printf("Websocket accepted: %s\n", addr)

	// Creating player.
	one := newPlayer(ws)

	// Adding player to sector.
	mainSector.addPlayer(one)

	// Spawing writing goroutine.
	go one.writer()

	// Sending player identification.
	one.ident()

	// Blocking this function on a reader.
	one.reader()

	// Reader has stopped, good bye!
	log.Printf("Websocket finalized: %s", addr)
}
开发者ID:hiroakiukaji,项目名称:shooter-server,代码行数:33,代码来源:main.go

示例4: serveWs

func serveWs(w http.ResponseWriter, r *http.Request) {
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", 405)
		return
	}

	// Read request details.
	r.ParseForm()
	iface := r.FormValue("if")
	if iface == "" {
		iface = "eth0"
	}

	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	c := &connection{send: make(chan []byte, 256), ws: ws, iface: iface}
	h.register <- c
	go c.writePump()
	c.readPump()
}
开发者ID:ngaut,项目名称:realtimetraffic,代码行数:26,代码来源:conn.go

示例5: websocketHandler

func websocketHandler(w http.ResponseWriter, r *http.Request) {

	conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024)
	addConnection(conn)
	listen(conn)

}
开发者ID:madhavgharmalkar,项目名称:HackUCI,代码行数:7,代码来源:websocket.go

示例6: wsHandler

func wsHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
	fmt.Println(r.Method)
	// Taken from gorilla's website
	conn, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}
	log.Println("Succesfully upgraded connection")
	connections[conn] = true

	for {
		// Blocks until a message is read
		_, msg, err := conn.ReadMessage()
		if err != nil {
			delete(connections, conn)
			conn.Close()
			return
		}
		log.Println(string(msg))
		sendAll(msg)
	}
}
开发者ID:natdm,项目名称:TwilioApp,代码行数:26,代码来源:main.go

示例7: Join

// Join method handles WebSocket requests for WebSocketController.
func (this *WebSocketController) Join() {
	uname := this.GetString("uname")
	if len(uname) == 0 {
		this.Redirect("/", 302)
		return
	}

	// Upgrade from http request to WebSocket.
	ws, err := websocket.Upgrade(this.Ctx.ResponseWriter, this.Ctx.Request, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(this.Ctx.ResponseWriter, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		beego.Error("Cannot setup WebSocket connection:", err)
		return
	}

	// Join chat room.
	Join(uname, ws)
	defer Leave(uname)

	// Message receive loop.
	for {
		_, p, err := ws.ReadMessage()
		if err != nil {
			return
		}
		publish <- newEvent(models.EVENT_MESSAGE, uname, string(p))
	}
}
开发者ID:elitecodegroovy,项目名称:GolangBestPractice,代码行数:31,代码来源:websocket.go

示例8: serveWs

func serveWs(w http.ResponseWriter, r *http.Request) {
	log.Print("serveWs")
	session, _ := store.Get(r, "session-name")
	if session.IsNew {
		log.Printf("rejecting ws without session from %v",
			r.RemoteAddr)
		return
	}
	ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)
	if _, ok := err.(websocket.HandshakeError); ok {
		log.Printf("rejecting ws with bad handshake from %v",
			r.RemoteAddr)
		http.Error(w, "Not a websocket handshake", 400)
		return
	} else if err != nil {
		log.Printf("serveWs error: %s", err.Error())
		return
	}
	log.Printf("serveWs ws connection from %v", r.RemoteAddr)
	c := &wsconn{send: make(chan []byte, 256), ws: ws}
	h.register <- c
	defer func() { h.unregister <- c }()
	go c.writer()
	c.reader()
}
开发者ID:ecashin,项目名称:go-getting,代码行数:25,代码来源:shform.go

示例9: notificationWSHandler

func notificationWSHandler(w http.ResponseWriter, r *http.Request) {
	sid := r.URL.Query()["sid"][0]

	cSession := coditorSessions.get(sid)

	if nil == cSession {
		return
	}

	conn, _ := websocket.Upgrade(w, r, nil, 1024, 1024)
	wsChan := util.WSChannel{Sid: sid, Conn: conn, Request: r, Time: time.Now()}

	ret := map[string]interface{}{"notification": "Notification initialized", "cmd": "init-notification"}
	err := wsChan.WriteJSON(&ret)
	if nil != err {
		return
	}

	notificationWS[sid] = &wsChan

	logger.Tracef("Open a new [Notification] with session [%s], %d", sid, len(notificationWS))

	// add user event handler
	cSession.EventQueue.addHandler(eventHandleFunc(event2Notification))

	input := map[string]interface{}{}

	for {
		if err := wsChan.ReadJSON(&input); err != nil {
			return
		}
	}
}
开发者ID:marswang,项目名称:coditorx,代码行数:33,代码来源:notification.go

示例10: handleConn

func (h *hub) handleConn(w http.ResponseWriter, r *http.Request) {
	conn, err := websocket.Upgrade(w, r, nil, 0, 0)
	ok(err)
	s := &stream{h: h, conn: conn}

	for {
		_, buf, err := conn.ReadMessage()
		if isReadFromClosedConnError(err) {
			log.Printf("conn closed: %v", err)
			break
		}
		ok(err)
		// TODO: Avoid decoding multiple times.
		var mt MsgType
		ok(json.Unmarshal(buf, &mt))
		switch mt.Type {
		case "SubscribeC2S":
			var msg SubscribeC2S
			ok(json.Unmarshal(buf, &msg))
			ok(s.processSubscribeC2S(&msg))
		case "SubscribeI2R":
			var msg SubscribeI2R
			ok(json.Unmarshal(buf, &msg))
			ok(s.processSubscribeI2R(&msg))
		case "PatchC2S":
			var msg PatchC2S
			ok(json.Unmarshal(buf, &msg))
			ok(s.processPatchC2S(&msg))
		default:
			panic(fmt.Errorf("unknown message type: %s", mt.Type))
		}
	}

	conn.Close()
}
开发者ID:asadovsky,项目名称:cdb,代码行数:35,代码来源:hub.go

示例11: WsHandler

func (b BackendController) WsHandler(writer http.ResponseWriter, request *http.Request) {
	conn, err := websocket.Upgrade(writer, request, nil, 1024, 1024)
	log.Println("getting a connection")
	if _, ok := err.(websocket.HandshakeError); ok {
		http.Error(writer, "got a websocket handshake", 400)
		return
	} else if err != nil {
		log.Println(err)
		return
	}

	b.ConnectionHandler(conn)
	defer b.CleanUpHandler(conn)      // if this function ever exits, clean up the data
	defer delete(b.connections, conn) // if this function ever exits, clean up the data

	b.connections[conn] = true

	for {
		_, msg, err := conn.ReadMessage()
		if err != nil {
			return
		}
		b.EventHandler(msg, conn)
	}
}
开发者ID:etinlb,项目名称:go_server_experiment,代码行数:25,代码来源:main.go

示例12: ServeHTTP

func (w *WebsocketServer) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	w.logger.Debug("WebsocketServer.ServeHTTP: starting")
	var handler wsHandler
	var err error

	paths := strings.Split(request.URL.Path, "/")
	endpointName := paths[1]

	if endpointName == "firehose" {
		handler, err = w.firehoseHandler(paths, writer, request)
	} else {
		handler, err = w.appHandler(paths, writer, request)
	}

	if err != nil {
		w.logger.Errorf("WebsocketServer.ServeHTTP: %s", err.Error())
		return
	}

	ws, err := gorilla.Upgrade(writer, request, nil, 1024, 1024)
	if err != nil {
		w.logger.Errorf("WebsocketServer.ServeHTTP: Upgrade error (returning 400): %s", err.Error())
		http.Error(writer, err.Error(), 400)
		return
	}

	defer func() {
		ws.WriteControl(gorilla.CloseMessage, gorilla.FormatCloseMessage(gorilla.CloseNormalClosure, ""), time.Time{})
		ws.Close()
	}()

	handler(ws)
}
开发者ID:yingkitw,项目名称:loggregator,代码行数:33,代码来源:websocket_server.go

示例13: upgradeRequest

// Upgrade the connection to a websocket connection
func upgradeRequest(resp http.ResponseWriter, req *http.Request, o *Options) (*websocket.Conn, int, error) {
	if req.Method != "GET" {
		o.log("Method %s is not allowed", LogLevelWarning, req.RemoteAddr, req.Method)
		return nil, http.StatusMethodNotAllowed, errors.New("Method not allowed")
	}

	allowedOrigin := replacementRegexp.ReplaceAllString(o.AllowedOrigin, req.Host)
	if r, err := regexp.MatchString(allowedOrigin, req.Header.Get("Origin")); !r || err != nil {
		o.log("Origin %s is not allowed", LogLevelWarning, req.RemoteAddr, req.Host)
		return nil, http.StatusForbidden, errors.New("Origin not allowed")
	}

	o.log("Request to %s has been allowed for origin %s", LogLevelDebug, req.RemoteAddr, req.Host, req.Header.Get("Origin"))

	ws, err := websocket.Upgrade(resp, req, nil, 1024, 1024)
	if handshakeErr, ok := err.(websocket.HandshakeError); ok {
		o.log("Handshake failed: %s", LogLevelWarning, req.RemoteAddr, handshakeErr)
		return nil, http.StatusBadRequest, handshakeErr
	} else if err != nil {
		o.log("Handshake failed: %s", LogLevelWarning, req.RemoteAddr, err)
		return nil, http.StatusBadRequest, err
	}

	o.log("Connection established", LogLevelInfo, req.RemoteAddr)
	return ws, http.StatusOK, nil
}
开发者ID:jmptrader,项目名称:martini-sockets,代码行数:27,代码来源:sockets.go

示例14: slashws

func slashws(w http.ResponseWriter, req *http.Request) {
	if req.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	if req.Header.Get("Origin") != "http://"+req.Host {
		http.Error(w, "Forbidden", http.StatusForbidden)
		return
	}
	ws, err := websocket.Upgrade(w, req, nil, 1024, 1024)
	if err != nil {
		if _, ok := err.(websocket.HandshakeError); ok {
			http.Error(w, "websocket.Upgrade errd", http.StatusBadRequest)
			return
		}
		panic(err)
	}

	wc := &wclient{ws: ws, ping: make(chan bool, 1)}
	register <- wc
	defer func() {
		unregister <- wc
	}()
	go wc.waitfor_messages() // read from client
	wc.waitfor_updates()     // write to  client
}
开发者ID:johntdyer,项目名称:golang-devops-stuff,代码行数:26,代码来源:ws.go

示例15: WsHandler

func (h *sockethub) WsHandler(w http.ResponseWriter, r *http.Request) {
	var authenticated bool

	if h.Auth != nil {
		authenticated = h.Auth(r)
	}

	if authenticated {
		ws, err := websocket.Upgrade(w, r, nil, 1024, 1024)

		if _, ok := err.(websocket.HandshakeError); ok {
			http.Error(w, "Not a websocket handshake", 400)
			return
		} else if err != nil {
			log.Printf("WsHandler error: %s", err.Error())
			return
		}

		c := &connection{send: make(chan *Data), ws: ws}
		h.register <- c

		defer func() { h.unregister <- c }()
		go c.writer()
		c.reader()
	} else {
		http.Error(w, "Invalid API key", 401)
	}
}
开发者ID:johnernaut,项目名称:goatee,代码行数:28,代码来源:notifier.go


注:本文中的github.com/gorilla/websocket.Upgrade函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。