// HandleHTTPWebSocket registers the WebSocket handler.
548590
func (m *Manager) HandleHTTPWebSocket(pattern string) {
	log.Infof("workflow Manager listening to websocket traffic at %v", pattern)
	http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if x := recover(); x != nil {
				errMsg := fmt.Sprintf("uncaught panic: %v", x)
				log.Error(errMsg)
				http.Error(w, errMsg, http.StatusInternalServerError)
			}
		}()

		// Check ACL.
		if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil {
			msg := fmt.Sprintf("WorkflowManager acl.CheckAccessHTTP failed: %v", err)
			log.Error(msg)
			http.Error(w, msg, http.StatusUnauthorized)
			return
		}

		// Upgrade to WebSocket.
		c, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Errorf("upgrade error: %v", err)
			return
		}
		defer c.Close()

		// Register the handler.
		tree, notifications, i, err := m.getAndWatchFullTree(r.URL)
		if err != nil {
			log.Warningf("GetAndWatchFullTree failed: %v", err)
			return
		}
		if notifications != nil {
			defer m.NodeManager().CloseWatcher(i)
		}

		// First we send the full dump
		if err := c.WriteMessage(websocket.TextMessage, tree); err != nil {
			log.Warningf("WriteMessage(tree) failed: %v", err)
			return
		}

		// If we didn't get a channel back (redirect case), we're done.
		// We will just return the redirect, and close the websocket.
		if notifications == nil {
			return
		}

		// Start a go routine to get messages, send them to a channel.
		recv := make(chan *ActionParameters, 10)
		go func() {
			for {
				mt, message, err := c.ReadMessage()
				if err != nil {
					log.Warningf("failed to read message from websocket: %v", err)
					close(recv)
					return
				}
				if mt != websocket.TextMessage {
					log.Warningf("weird message type: %v", mt)
				}

				ap := &ActionParameters{}
				if err := json.Unmarshal(message, ap); err != nil {
					log.Warningf("failed to JSON-decode message from websocket: %v", err)
					close(recv)
					return
				}
				recv <- ap
			}
		}()

		// Let's listen to the channels until we're done.
		for {
			select {
			case ap, ok := <-recv:
				if !ok {
					// The websocket was most likely closed.
					return
				}

				ctx := context.TODO()
				if err := m.NodeManager().Action(ctx, ap); err != nil {
					log.Warningf("Action failed: %v", err)
				}

			case message, ok := <-notifications:
				if !ok {
					// We ran out of space on the update
					// channel, so we had to close it.
					return
				}
				if err := c.WriteMessage(websocket.TextMessage, message); err != nil {
					log.Warningf("WriteMessage(tree) failed: %v", err)
					return
				}
			}
		}
	})
}
447189
func Websocket(route string, httpHandler websocket.Handler) {
	mainServer.Websocket(route, httpHandler)
}
8398
func (s *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	s.router.ServeHTTP(w, req)
}
981109
func (ro *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	rd := ro.pickupBestRouteDefinition(r)

	if rd == nil {
		http.NotFound(w, r)
		return
	}

	ctx := getDefaultContext(r)

	match, params := rd.PathTemplate.Match(encodedPathFromRequest(r))
	if !match {
		http.Error(w, "[ucon] invalid handler picked", http.StatusInternalServerError)
		return
	}
	ctx = context.WithValue(ctx, PathParameterKey, params)

	b, err := ro.mux.newBubble(ctx, w, r, rd)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	err = b.Next()
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}
151638
func (h *Handler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
	h.ServeHTTPC(h.StartingContext, rw, r)
}
1147132
func DialWebsocket(uri string, cfg *config.Config) (*WebsocketSession, error) {
	u, err := url.Parse(uri)
	if err != nil {
		return nil, err
	}

	h := http.Header{
		"Origin": {u.Scheme + "://" + u.Host},
	}

	serverID := threeDigits()
	sessionID := utils.RandomString(20)

	u = makeWebsocketURL(u, serverID, sessionID)

	conn, _, err := cfg.Websocket.Dial(u.String(), h)
	if err != nil {
		return nil, err
	}

	session := NewWebsocketSession(conn)
	session.id = sessionID
	session.req = &http.Request{
		URL:    u,
		Header: h,
	}

	return session, nil
}
544150
func (f ApiHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	f(w, r)
}
365428
func (cniApp *cniAppInfo) handleHTTP(url string, jsonReq *bytes.Buffer) int {

	cniLog.Infof("http POST url: %s data: %v", url, jsonReq)
	httpResp, err := cniApp.httpClient.Post(url, "application/json", jsonReq)
	if err != nil {
		return cniApp.sendCniErrorResp("failed to get response from netplugin :" + err.Error())
	}
	defer httpResp.Body.Close()

	switch httpResp.StatusCode {

	case http.StatusOK:
		cniLog.Infof("received http OK response from netplugin")
		info, err := ioutil.ReadAll(httpResp.Body)
		if err != nil {
			return cniApp.sendCniErrorResp("failed to read success response from netplugin :" + err.Error())
		}
		return cniApp.sendCniResp(info, cniapi.CniStatusSuccess)

	case http.StatusInternalServerError:
		cniLog.Infof("received http error response from netplugin")
		info, err := ioutil.ReadAll(httpResp.Body)
		if err != nil {
			return cniApp.sendCniErrorResp("failed to read error response from netplugin :" + err.Error())
		}
		return cniApp.sendCniResp(info, cniapi.CniStatusErrorUnsupportedField)

	default:
		cniLog.Infof("received unknown error from netplugin")
		return cniApp.sendCniErrorResp("error response from netplugin: " + http.StatusText(httpResp.StatusCode))
	}
}
379697
func (xc *CommonExchange) startWebsocket() {
	ws, processor := xc.websocket()
	go func() {
		for {
			message, err := ws.Read()
			if err != nil {
				xc.setWsFail(err)
				return
			}
			processor(message)
		}
	}()
}
1046558
func (s *Server) Websocket(route string, httpHandler websocket.Handler) {
	s.addRoute(route, "GET", httpHandler)
}
767931
func (s *Server) handleOnNewSocketConnection(bs backend.BackendSocket) {
	// Close the socket if incomming connections should be blocked.
	if s.IsBlocked() {
		bs.Close()
		return
	}

	// Create a new socket value.
	// The goroutines are started automatically.
	newSocket(s, bs)
}
635060
func NewWebsocketManager(funcMap map[string]*RPCFunc, logger *logging.Logger,
	wsConnOptions ...func(*wsConnection)) *WebsocketManager {
	return &WebsocketManager{
		funcMap: funcMap,
		Upgrader: websocket.Upgrader{
			CheckOrigin: func(r *http.Request) bool {
				// TODO ???
				return true
			},
		},
		logger:        logger,
		wsConnOptions: wsConnOptions,
	}
}
187955
func (server *Server) HandleHTTP(rpcPath, debugPath string) {
	http.Handle(rpcPath, server)
	http.Handle(debugPath, debugHTTP{server})
}
1085872
func (g *GitHttp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	g.requestHandler(w, r)
	return
}
1141457
func (service *WebSocketService) ServeHTTP(
	response http.ResponseWriter, request *http.Request) {
	if request.Method == "GET" && !strings.Contains(strings.ToLower(request.Header.Get("connection")), "upgrade") || request.Method == "POST" || request.Method == "OPTIONS" {
		service.HTTPService.ServeHTTP(response, request)
		return
	}
	conn, err := service.Upgrade(response, request, nil)
	if err != nil {
		context := new(rpc.HTTPContext)
		context.InitHTTPContext(service, response, request)
		resp := service.EndError(err, context)
		response.Header().Set("Content-Length", util.Itoa(len(resp)))
		response.Write(resp)
		return
	}
	defer conn.Close()

	mutex := new(sync.Mutex)
	for {
		msgType, data, err := conn.ReadMessage()
		if err != nil {
			break
		}
		if msgType == websocket.BinaryMessage {
			go service.handle(data, mutex, response, request, conn)
		}
	}
}
958788
func (conn *Conn) handle(ws *websocket.Conn) {
	defer conn.Close()
	conn.initialize(ws)

	for {
		conn.resetTimeout()
		var data []byte
		if err := websocket.Message.Receive(ws, &data); err != nil {
			if err != io.EOF {
				glog.Errorf("Error on socket receive: %v", err)
			}
			break
		}
		if len(data) == 0 {
			continue
		}
		channel := data[0]
		if conn.codec == base64Codec {
			channel = channel - '0'
		}
		data = data[1:]
		if int(channel) >= len(conn.channels) {
			glog.V(6).Infof("Frame is targeted for a reader %d that is not valid, possible protocol error", channel)
			continue
		}
		if _, err := conn.channels[channel].DataFromSocket(data); err != nil {
			glog.Errorf("Unable to write frame to %d: %v\n%s", channel, err, string(data))
			continue
		}
	}
}
1183813
func (fe *T) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fe.getHandler().ServeHTTP(w, r)
}