// WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections.
//
// allowedOrigins should be a comma-separated list of allowed origin URLs.
// To allow connections with any origin, pass "*".
328677
func (s *Server) WebsocketHandler(allowedOrigins []string) http.Handler {
	return websocket.Server{
		Handshake: wsHandshakeValidator(allowedOrigins),
		Handler: func(conn *websocket.Conn) {
			codec := newWebsocketCodec(conn)
			s.ServeCodec(codec, OptionMethodInvocation|OptionSubscriptions)
		},
	}
}
573021
func initJWTAuthHandler() func(ctx *neptulon.ReqCtx) error {
	return func(ctx *neptulon.ReqCtx) error {
		// todo: this could rather send the remaining queue size for the client so client can disconnect if there is nothing else to do
		ctx.Res = client.ACK
		return ctx.Next()
	}
}
1067565
func NewHandlerSwitcher(newHandler http.Handler) (hs *HTTPHandlerSwitcher) {
	return &HTTPHandlerSwitcher{
		handler: safe.New(newHandler),
	}
}
968
func PubSubHandler(ctx *router.Context) {
	statusCode := pubSubHandlerImpl(ctx.Context, ctx.Request)
	ctx.Writer.WriteHeader(statusCode)
}
166813
func (s *CORSRule) SetAllowedOrigins(v []*string) *CORSRule {
	s.AllowedOrigins = v
	return s
}
148010
func AllowRequestsFrom(allowedOrigins ...string) http.HandlerFunc {
	c := &CORS{
		AllowOrigins: allowedOrigins,
		AllowMethods: []string{"GET", "POST"},
		AllowHeaders: []string{"Origin", "Content-Type"},
		ContentType:  "application/json; charset=utf-8",
	}

	c.generatePatterns()

	return func(w http.ResponseWriter, req *http.Request) {
		origin := req.Header.Get("Origin")
		if c.isOriginAllowed(origin) {
			w.Header().Set("Access-Control-Allow-Origin", origin)
			w.Header().Set("Access-Control-Allow-Headers", c.AllowedHeaders())
			w.Header().Set("Access-Control-Allow-Methods", c.AllowedMethods())
			w.Header().Set("Content-Type", c.ContentType)
		}
	}
}
832725
func (cfgSrcHandler *Handler) DynamicConfigHandler(callback core.DynamicConfigCallback) error {
	if cfgSrcHandler.initSuccess != true {
		return errors.New("config center source initialization failed")
	}

	dynCfgHandler, err := newDynConfigHandlerSource(cfgSrcHandler, callback)
	if err != nil {
		openlogging.GetLogger().Error("failed to initialize dynamic config center Handler:" + err.Error())
		return errors.New("failed to initialize dynamic config center Handler")
	}
	cfgSrcHandler.dynamicConfigHandler = dynCfgHandler

	if cfgSrcHandler.RefreshMode == 0 {
		// Pull All the configuration for the first time.
		cfgSrcHandler.refreshConfigurations("")
		//Start a web socket connection to recieve change events.
		dynCfgHandler.startDynamicConfigHandler()
	}

	return nil
}
416922
func isDeprecatedSocketDirAllowed(versions []string) bool {
	for _, version := range versions {
		if isV0Version(version) {
			return true
		}
	}

	return false
}
1350464
func CorsHandler(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		jsonp := false
		if cbName := req.FormValue("callback"); cbName != "" && req.Method == "GET" {
			rw.Header().Set("Content-Type", "text/javascript")
			rw.Write([]byte(fmt.Sprintf("%v(", cbName)))
			jsonp = true
		} else {
			rw.Header().Set("Content-Type", "application/json")
			if origin := req.Header.Get("Origin"); origin != "" {
				rw.Header().Add("Access-Control-Allow-Origin", origin)
			}
			if methods := req.Header.Get("Access-Control-Request-Method"); methods != "" {
				rw.Header().Add("Access-Control-Allow-Methods", methods)
			}
			if headers := req.Header.Get("Access-Control-Request-Headers"); headers != "" {
				rw.Header().Add("Access-Control-Allow-Headers", headers)
			}
			rw.Header().Add("Access-Control-Allow-Credentials", "true")

			// If we're getting an OPTIONS request, just send response
			if req.Method == "OPTIONS" {
				rw.WriteHeader(http.StatusOK)
				return
			}
		}
		handler.ServeHTTP(rw, req)
		if jsonp {
			rw.Write([]byte(");"))
		}
	})
}
890391
func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) {
	w.Write(f.index)
}
405003
func (s *peerRESTServer) SignalServiceHandler(w http.ResponseWriter, r *http.Request) {
	if !s.IsValid(w, r) {
		s.writeErrorResponse(w, errors.New("Invalid request"))
		return
	}

	vars := mux.Vars(r)
	signalString := vars[peerRESTSignal]
	if signalString == "" {
		s.writeErrorResponse(w, errors.New("signal name is missing"))
		return
	}
	signal := serviceSignal(signalString)
	defer w.(http.Flusher).Flush()
	switch signal {
	case serviceRestart, serviceStop:
		globalServiceSignalCh <- signal
	default:
		s.writeErrorResponse(w, errUnsupportedSignal)
		return
	}
}
1069078
func allowCORS(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if origin := r.Header.Get("Origin"); origin != "" {
			w.Header().Set("Access-Control-Allow-Origin", origin)
			if r.Method == "OPTIONS" && r.Header.Get("Access-Control-Request-Method") != "" {
				preflightHandler(w, r)
				return
			}
		}
		h.ServeHTTP(w, r)
	})
}
130391
func HeadersHandler(w http.ResponseWriter, r *http.Request) {
	if err := writeJSON(w, headersResponse{getHeaders(r)}); err != nil {
		writeErrorJSON(w, errors.Wrap(err, "failed to write json"))
	}
}
913817
func bridgedStreamingRpcHandler(sideA io.ReadWriteCloser) structs.StreamingRpcHandler {
	return func(sideB io.ReadWriteCloser) {
		defer sideA.Close()
		defer sideB.Close()
		structs.Bridge(sideA, sideB)
	}
}
1319852
func WsFastHandler(ctx *fasthttp.RequestCtx) {
	upgrader := fastwebsocket.New(func(c *fastwebsocket.Conn) {
		defer c.Close()
		for {
			mt, message, err := c.ReadMessage()
			if err != nil {
				break
			}
			err = c.WriteMessage(mt, message)
			if err != nil {
				break
			}
		}
	})
	err := upgrader.Upgrade(ctx)
	if err != nil {
		panic(err)
	}
}
130666
func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger *logging.Logger) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			WriteRPCResponseHTTP(w, types.RPCInvalidRequestError("", errors.Wrap(err, "Error reading request body")))
			return
		}
		// if its an empty request (like from a browser),
		// just display a list of functions
		if len(b) == 0 {
			writeListOfEndpoints(w, r, funcMap)
			return
		}

		var request types.RPCRequest
		err = json.Unmarshal(b, &request)
		if err != nil {
			WriteRPCResponseHTTP(w, types.RPCParseError("", errors.Wrap(err, "Error unmarshalling request")))
			return
		}
		// A Notification is a Request object without an "id" member.
		// The Server MUST NOT reply to a Notification, including those that are within a batch request.
		if request.ID == "" {
			logger.TraceMsg("HTTPJSONRPC received a notification, skipping... (please send a non-empty ID if you want to call a method)")
			return
		}
		if len(r.URL.Path) > 1 {
			WriteRPCResponseHTTP(w, types.RPCInvalidRequestError(request.ID, errors.Errorf("Path %s is invalid", r.URL.Path)))
			return
		}
		rpcFunc := funcMap[request.Method]
		if rpcFunc == nil || rpcFunc.ws {
			WriteRPCResponseHTTP(w, types.RPCMethodNotFoundError(request.ID))
			return
		}
		var args []reflect.Value
		if len(request.Params) > 0 {
			args, err = jsonParamsToArgsRPC(rpcFunc, request.Params)
			if err != nil {
				WriteRPCResponseHTTP(w, types.RPCInvalidParamsError(request.ID, errors.Wrap(err, "Error converting json params to arguments")))
				return
			}
		}
		returns := rpcFunc.f.Call(args)
		logger.InfoMsg("HTTP JSONRPC called", "method", request.Method, "args", args, "returns", returns)
		result, err := unreflectResult(returns)
		if err != nil {
			WriteRPCResponseHTTP(w, types.RPCInternalError(request.ID, err))
			return
		}
		WriteRPCResponseHTTP(w, types.NewRPCSuccessResponse(request.ID, result))
	}
}
1258457
func NewHandlerWrapper() server.HandlerWrapper {
	return func(fn server.HandlerFunc) server.HandlerFunc {
		return func(ctx context.Context, req server.Request, rsp interface{}) (err error) {
			t := newRequestTracker(req, ServerProfile)
			ctx = t.start(ctx, false)

			defer func() { t.end(ctx, err) }()

			spanCtx := getTraceFromCtx(ctx)
			if spanCtx != nil {
				ctx, t.span = trace.StartSpanWithRemoteParent(
					ctx,
					fmt.Sprintf("rpc/%s/%s/%s", ServerProfile.Role, req.Service(), req.Endpoint()),
					*spanCtx,
				)
			} else {
				ctx, t.span = trace.StartSpan(
					ctx,
					fmt.Sprintf("rpc/%s/%s/%s", ServerProfile.Role, req.Service(), req.Endpoint()),
				)
			}

			err = fn(ctx, req, rsp)
			return
		}
	}
}