// Handler is a HandlerFunc handling the livereload
// Websocket interaction.
974058
func Handler(w http.ResponseWriter, r *http.Request) {
	ws, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		return
	}
	c := &connection{send: make(chan []byte, 256), ws: ws}
	wsHub.register <- c
	defer func() { wsHub.unregister <- c }()
	go c.writer()
	c.reader()
}
903233
func (f HandlerFunc) Handle(c *Client, m *Message) {
	f(c, m)
}
1280328
func (h *Hitch) Handler() http.Handler {
	handler := http.Handler(h.Router)
	for i := len(h.middleware) - 1; i >= 0; i-- {
		handler = h.middleware[i](handler)
	}
	return handler
}
410134
func (s *handler) handler(srv interface{}, serverStream grpc.ServerStream) error {
	// little bit of gRPC internals never hurt anyone
	fullMethodName, ok := grpc.MethodFromServerStream(serverStream)
	if !ok {
		return grpc.Errorf(codes.Internal, "lowLevelServerStream not exists in context")
	}
	// We require that the director's returned context inherits from the serverStream.Context().
	outgoingCtx, backendConn, err := s.director(serverStream.Context(), fullMethodName)
	if err != nil {
		return err
	}

	clientCtx, clientCancel := context.WithCancel(outgoingCtx)
	// TODO(mwitkow): Add a `forwarded` header to metadata, https://en.wikipedia.org/wiki/X-Forwarded-For.
	clientStream, err := grpc.NewClientStream(clientCtx, clientStreamDescForProxying, backendConn, fullMethodName)
	if err != nil {
		return err
	}
	// Explicitly *do not close* s2cErrChan and c2sErrChan, otherwise the select below will not terminate.
	// Channels do not have to be closed, it is just a control flow mechanism, see
	// https://groups.google.com/forum/#!msg/golang-nuts/pZwdYRGxCIk/qpbHxRRPJdUJ
	s2cErrChan := s.forwardServerToClient(serverStream, clientStream)
	c2sErrChan := s.forwardClientToServer(clientStream, serverStream)
	// We don't know which side is going to stop sending first, so we need a select between the two.
	for i := 0; i < 2; i++ {
		select {
		case s2cErr := <-s2cErrChan:
			if s2cErr == io.EOF {
				// this is the happy case where the sender has encountered io.EOF, and won't be sending anymore./
				// the clientStream>serverStream may continue pumping though.
				clientStream.CloseSend()
				break
			} else {
				// however, we may have gotten a receive error (stream disconnected, a read error etc) in which case we need
				// to cancel the clientStream to the backend, let all of its goroutines be freed up by the CancelFunc and
				// exit with an error to the stack
				clientCancel()
				return grpc.Errorf(codes.Internal, "failed proxying s2c: %v", s2cErr)
			}
		case c2sErr := <-c2sErrChan:
			// This happens when the clientStream has nothing else to offer (io.EOF), returned a gRPC error. In those two
			// cases we may have received Trailers as part of the call. In case of other errors (stream closed) the trailers
			// will be nil.
			serverStream.SetTrailer(clientStream.Trailer())
			// c2sErr will contain RPC error from client code. If not io.EOF return the RPC error as server stream error.
			if c2sErr != io.EOF {
				return c2sErr
			}
			return nil
		}
	}
	return grpc.Errorf(codes.Internal, "gRPC proxying should never reach this stage.")
}
1105936
func (d *SUIData3) Handler(notFound http.Handler, defaultDef string) http.Handler {
	return suihttp.Handler(d.as, notFound, d.index, d.def, defaultDef)
}
276838
func Handler(c *gin.Context) {
	startTime := time.Now()
	c.Next()
	if agent != nil {
		agent.HTTPTimer.UpdateSince(startTime)
	}
}
1372081
func (o *Options) Handler(next http.Handler) http.HandlerFunc {
	// Allow default headers if nothing is specified.
	if len(o.AllowHeaders) == 0 {
		o.AllowHeaders = defaultAllowHeaders
	}

	for _, origin := range o.AllowOrigins {
		pattern := regexp.QuoteMeta(origin)
		pattern = strings.Replace(pattern, "\\*", ".*", -1)
		pattern = strings.Replace(pattern, "\\?", ".", -1)
		allowOriginPatterns = append(allowOriginPatterns, "^"+pattern+"$")
	}

	return func(w http.ResponseWriter, req *http.Request) {
		if origin := req.Header.Get(headerOrigin); origin != "" {
			for key, value := range o.Header(origin, req) {
				w.Header().Set(key, value)
			}
			if req.Method == "OPTIONS" {
				w.WriteHeader(200)
				return
			}
		}
		next.ServeHTTP(w, req)
	}
}
693629
func (om *Oauth2oauth_2_0Middleware) Handler(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var atscopestring string
		var username string
		var clientID string
		authorizedScopes := []string{}

		accessToken := om.GetAccessToken(r)

		token, err := oauth2.GetValidJWT(r, security.JWTPublicKey)
		if err != nil {
			log.Error(err)
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return
		}
		if token != nil {
			username = token.Claims["username"].(string)
			clientID = token.Claims["azp"].(string)
			atscopestring = oauth2.GetScopestringFromJWT(token)

		} else if accessToken != "" {
			//TODO: cache
			oauthMgr := oauthservice.NewManager(r)
			at, err := oauthMgr.GetAccessToken(accessToken)
			if err != nil {
				log.Error(err)
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				return
			}
			if at == nil {
				http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
				return
			}
			username = at.Username
			atscopestring = at.Scope
			clientID = at.ClientID
		} else {
			if webuser, ok := context.GetOk(r, "webuser"); ok {
				if parsedusername, ok := webuser.(string); ok && parsedusername != "" {
					username = parsedusername
					atscopestring = "admin"
					clientID = "itsyouonline"
				}
			}
		}
		log.Debugln("Accessing user:", username, "- Accessing clientID:", clientID)
		if username == "" || clientID == "" {
			http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
			return
		}

		protectedUsername := mux.Vars(r)["username"]

		for _, scope := range strings.Split(atscopestring, ",") {
			scope = strings.Trim(scope, " ")
			authorizedScopes = append(authorizedScopes, scope)
		}

		possibleScopes := []string{}
		// Replace {variables} in the scopes with the real vars present in the url.
		for _, scope := range om.Scopes {
			regex, _ := regexp.Compile(`\{(.*?)\}`)
			vars := regex.FindStringSubmatch(scope)
			if vars != nil {
				// e.g. vars -> ["{label}", "label"]
				re, _ := regexp.Compile(vars[0])
				urlValue := mux.Vars(r)[vars[1]]
				scope = re.ReplaceAllString(scope, urlValue)
			}
			possibleScopes = append(possibleScopes, scope)
		}

		// atscopestring will be user:admin for user api keys, which is only valid if the api key is owned by the user being accessed off course
		if !((protectedUsername == username && atscopestring == "user:admin") || (clientID == "itsyouonline" && atscopestring == "admin")) {
			// todo: cache
			userMgr := user.NewManager(r)
			authorization, err := userMgr.GetAuthorization(protectedUsername, clientID)
			if err != nil {
				log.Error("Error while getting authorization: ", err)
				http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
				return
			}
			if authorization == nil {
				// Check if this is client credentials
				keyFound, err := apikey.NewManager(r).Exists(protectedUsername, clientID)
				if err != nil {
					log.Error("Failed tocheck if user api key exists: ", err)
					http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
					return
				}
				// If there are no matching appIds, the permission has been revoked
				if !keyFound {
					log.Debugf("Authorization for client id %s not found for user %s", clientID, protectedUsername)
					http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
					return
				}
			} else {
				authorizedScopes = authorization.FilterAuthorizedScopes(authorizedScopes)
			}
		}

		if protectedUsername == username && clientID == "itsyouonline" && atscopestring == "admin" {
			authorizedScopes = append(authorizedScopes, "user:admin")
		}
		if strings.HasPrefix(atscopestring, "user:") {
			authorizedScopes = append(authorizedScopes, "user:info")
		}

		idAzp := context.Get(r, "iyoid_azp")
		if idAzp != nil && idAzp.(string) != clientID {
			log.Debugf("Iyo id azp from the user identifier and client ID mismatch: client: %s, iyo id belongs to %s", clientID, idAzp.(string))
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		context.Set(r, "client_id", clientID)
		context.Set(r, "availablescopes", strings.Join(authorizedScopes, ","))

		// check scopes
		log.Debug("Authorized scopes: ", authorizedScopes)
		log.Debug("Needed possible scopes: ", possibleScopes)
		if !oauth2.CheckScopes(possibleScopes, authorizedScopes) {
			http.Error(w, http.StatusText(http.StatusForbidden), http.StatusForbidden)
			return
		}

		next.ServeHTTP(w, r)
	})
}
360790
func (mw *Middleware) Handler() http.Handler {
	//Initialize with an empty http.Handler
	next := emptyHandler

	//Call the middleware stack in FIFO order
	for i := len(mw.Wares) - 1; i >= 0; i-- {
		next = mw.Wares[i](next)
	}
	return next
}
64999
func (s *Server) Handle(typ string, f protocolHandler) {
	s.handlers[typ] = f
}
1256731
func Handle(route string, method string, httpHandler http.Handler) {
	mainServer.Handle(route, method, httpHandler)
}
1013392
func (r *Router) handle(handlerName string, h http.HandlerFunc) httprouter.Handle {
	if r.instrh != nil {
		// This needs to be outside the closure to avoid data race when reading and writing to 'h'.
		h = r.instrh(handlerName, h)
	}
	return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		ctx, cancel := context.WithCancel(req.Context())
		defer cancel()

		for _, p := range params {
			ctx = context.WithValue(ctx, param(p.Key), p.Value)
		}
		h(w, req.WithContext(ctx))
	}
}
1135239
func (h HandlerFunc) Handle(data json.RawMessage, ctx *apex.Context) (interface{}, error) {
	var event Event

	if err := json.Unmarshal(data, &event); err != nil {
		return nil, err
	}

	return nil, h(&event, ctx)
}
904983
func (f HandlerFunc) Handle(im *Image, params Params) (*Image, error) {
	return f(im, params)
}
301961
func (r *Router) Handle(event string, h http.Handler) {
	r.routes[event] = h
}
308464
func (eh webhooksUpdateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*WebhooksUpdate); ok {
		eh(s, t)
	}
}
972679
func (router *Router) Handler() func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		// Check if method used was GET.
		if r.Method != "GET" {
			http.Error(w, "Method not allowed", 405)
			return
		}

		// Disallow cross-origin connections.
		if len(router.Origins) > 0 {
			originFound := false
			for _, origin := range router.Origins {
				if r.Header.Get("Origin") == origin {
					originFound = true
					break
				}
			}
			if !originFound {
				http.Error(w, "Origin not allowed", 403)
				return
			}
		} else {
			if len(r.Header.Get("Access-Control-Allow-Origin")) > 0 {
				allowedOrigin := r.Header.Get("Access-Control-Allow-Origin")
				if allowedOrigin != "*" {
					if r.URL.Scheme+"://"+r.Host != allowedOrigin {
						http.Error(w, "Origin not allwed", 403)
						return
					}
				}
			}
		}

		// Check if handshake callback verifies upgrade.
		if !router.handshakeFunc(w, r) {
			http.Error(w, "Authorization failed", 403)
			return
		}

		// Upgrade websocket connection.
		protocols := websocket.Subprotocols(r)
		var responseHeader http.Header = nil
		if len(protocols) > 0 {
			responseHeader = http.Header{"Sec-Websocket-Protocol": {protocols[0]}}
		}
		socket, err := websocket.Upgrade(w, r, responseHeader, 1024, 1024)
		// Check if handshake was successful
		if _, ok := err.(websocket.HandshakeError); ok {
			http.Error(w, "Not a websocket handshake", 400)
			return
		} else if err != nil {
			log.Println(err)
			return
		}

		// Create the connection.
		conn := newConnection(socket, router)
		//
		if router.connExtensionConstructor.IsValid() {
			conn.extend(router.connExtensionConstructor.Call([]reflect.Value{reflect.ValueOf(conn)})[0].Interface())
		}

		// Connection established with possible extension, so callback
		router.connectionFunc(conn, r)

		// And start reading and writing routines.
		conn.run()
	}
}