// serveRequests serve REST api requests
499768
func (ag *Agent) serveRequests() {
	listenURL := ":9090"
	router := mux.NewRouter()

	// Add REST routes
	s := router.Methods("GET").Subrouter()
	s.HandleFunc("/svcstats", func(w http.ResponseWriter, r *http.Request) {
		stats, err := ag.netPlugin.GetEndpointStats()
		if err != nil {
			log.Errorf("Error fetching stats from driver. Err: %v", err)
			http.Error(w, "Error fetching stats from driver", http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write(stats)
	})
	s.HandleFunc("/inspect/driver", func(w http.ResponseWriter, r *http.Request) {
		driverState, err := ag.netPlugin.InspectState()
		if err != nil {
			log.Errorf("Error fetching driver state. Err: %v", err)
			http.Error(w, "Error fetching driver state", http.StatusInternalServerError)
			return
		}
		w.Write(driverState)
	})
	s.HandleFunc("/inspect/bgp", func(w http.ResponseWriter, r *http.Request) {
		bgpState, err := ag.netPlugin.InspectBgp()
		if err != nil {
			log.Errorf("Error fetching bgp. Err: %v", err)
			http.Error(w, "Error fetching bgp", http.StatusInternalServerError)
			return
		}
		w.Write(bgpState)
	})

	s.HandleFunc("/inspect/nameserver", func(w http.ResponseWriter, r *http.Request) {
		ns, err := ag.netPlugin.NetworkDriver.InspectNameserver()
		if err != nil {
			log.Errorf("Error fetching nameserver state. Err: %v", err)
			http.Error(w, "Error fetching nameserver state", http.StatusInternalServerError)
			return
		}
		w.Write(ns)
	})

	s = router.Methods("Delete").Subrouter()
	s.HandleFunc("/debug/reclaimEndpoint/{id}", utils.MakeHTTPHandler(ag.ReclaimEndpointHandler))

	// Create HTTP server and listener
	server := &http.Server{Handler: router}
	listener, err := net.Listen("tcp", listenURL)
	if nil != err {
		log.Fatalln(err)
	}

	log.Infof("Netplugin listening on %s", listenURL)

	// start server
	go server.Serve(listener)
}
485899
func (d *CachedDiscoveryClient) ServerResources() ([]*metav1.APIResourceList, error) {
	_, rs, err := discovery.ServerGroupsAndResources(d)
	return rs, err
}
699316
func (s *HTTPServer) AgentServersRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	switch req.Method {
	case "PUT", "POST":
		return s.updateServers(resp, req)
	case "GET":
		return s.listServers(resp, req)
	default:
		return nil, CodedError(405, ErrInvalidMethod)
	}
}
127506
func (tm *TrustMetric) processRequests() {
	t := tm.testTicker
	if t == nil {
		// No test ticker was provided, so we create a normal ticker
		t = NewTicker(tm.intervalLen)
	}
	defer t.Stop()
	// Obtain the raw channel
	tick := t.GetChannel()
loop:
	for {
		select {
		case <-tick:
			tm.NextTimeInterval()
		case <-tm.Quit():
			// Stop all further tracking for this metric
			break loop
		}
	}
}
948717
func (n *rpcObserver) ServerReply(req rpc.Request, hdr *rpc.Header, body interface{}) {
	if req.Type == "Pinger" && req.Action == "Ping" {
		n.logReplyTrace(n.pingLogger, hdr, body)
		return
	}

	// TODO(rog) 2013-10-11 remove secrets from some responses.
	// Until secrets are removed, we only log the body of the requests at trace level
	// which is below the default level of debug.
	if n.logger.IsTraceEnabled() {
		n.logReplyTrace(n.logger, hdr, body)
	} else {
		n.logger.Debugf(
			"-> [%X] %s %s %s %s[%q].%s",
			n.id,
			n.tag,
			time.Since(n.requestStart),
			jsoncodec.DumpRequest(hdr, "'body redacted'"),
			req.Type,
			req.Id,
			req.Action,
		)
	}
}
1124709
func ParseRequest(contentType string, body io.Reader) (*Request, error) {
	if err := checkContentType(contentType); err != nil {
		return nil, err
	}

	r := &Request{}
	if err := parseReqOrResp(body, r); err != nil {
		return nil, err
	}

	return r, nil
}
425567
func (s *HTTPServer) JobsParseRequest(resp http.ResponseWriter, req *http.Request) (interface{}, error) {
	if req.Method != http.MethodPut && req.Method != http.MethodPost {
		return nil, CodedError(405, ErrInvalidMethod)
	}

	args := &api.JobsParseRequest{}
	if err := decodeBody(req, &args); err != nil {
		return nil, CodedError(400, err.Error())
	}
	if args.JobHCL == "" {
		return nil, CodedError(400, "Job spec is empty")
	}

	jobfile := strings.NewReader(args.JobHCL)
	jobStruct, err := jobspec.Parse(jobfile)
	if err != nil {
		return nil, CodedError(400, err.Error())
	}

	if args.Canonicalize {
		jobStruct.Canonicalize()
	}
	return jobStruct, nil
}
257230
func UpgradeRequests(pattern string, eventHandler EventHandler) {
	http.HandleFunc(pattern, UpgradeHandlerFunc(eventHandler))
}
216495
func (ls *ListServiceOfferings) ListRequest() (ListCommand, error) {
	if ls == nil {
		return nil, fmt.Errorf("%T cannot be nil", ls)
	}
	return ls, nil
}
489770
func (adm *AdminClient) ServerInfo() ([]ServerInfo, error) {
	resp, err := adm.executeMethod("GET", requestData{relPath: "/v1/info"})
	defer closeResponse(resp)
	if err != nil {
		return nil, err
	}

	// Check response http status code
	if resp.StatusCode != http.StatusOK {
		return nil, httpRespToErrorResponse(resp)
	}

	// Unmarshal the server's json response
	var serversInfo []ServerInfo

	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	err = json.Unmarshal(respBytes, &serversInfo)
	if err != nil {
		return nil, err
	}

	return serversInfo, nil
}
524084
func (s *Server) handleRequest(req *Request, conn conn) error {
	ctx := context.Background()

	// Resolve the address if we have a FQDN
	dest := req.DestAddr
	if dest.FQDN != "" {
		ctx_, addr, err := s.config.Resolver.Resolve(ctx, dest.FQDN)
		if err != nil {
			if err := sendReply(conn, hostUnreachable, nil); err != nil {
				return fmt.Errorf("Failed to send reply: %v", err)
			}
			return fmt.Errorf("Failed to resolve destination '%v': %v", dest.FQDN, err)
		}
		ctx = ctx_
		dest.IP = addr
	}

	// Apply any address rewrites
	req.realDestAddr = req.DestAddr
	if s.config.Rewriter != nil {
		ctx, req.realDestAddr = s.config.Rewriter.Rewrite(ctx, req)
	}

	// Switch on the command
	switch req.Command {
	case ConnectCommand:
		return s.handleConnect(ctx, conn, req)
	case BindCommand:
		return s.handleBind(ctx, conn, req)
	case AssociateCommand:
		return s.handleAssociate(ctx, conn, req)
	default:
		if err := sendReply(conn, commandNotSupported, nil); err != nil {
			return fmt.Errorf("Failed to send reply: %v", err)
		}
		return fmt.Errorf("Unsupported command: %v", req.Command)
	}
}
1066843
func (b *Backend) HandleRequest(ctx context.Context, req *logical.Request) (*logical.Response, error) {
	b.once.Do(b.init)

	// Check for special cased global operations. These don't route
	// to a specific Path.
	switch req.Operation {
	case logical.RenewOperation:
		fallthrough
	case logical.RevokeOperation:
		return b.handleRevokeRenew(ctx, req)
	case logical.RollbackOperation:
		return b.handleRollback(ctx, req)
	}

	// If the path is empty and it is a help operation, handle that.
	if req.Path == "" && req.Operation == logical.HelpOperation {
		return b.handleRootHelp()
	}

	// Find the matching route
	path, captures := b.route(req.Path)
	if path == nil {
		return nil, logical.ErrUnsupportedPath
	}

	// Check if a feature is required and if the license has that feature
	if path.FeatureRequired != license.FeatureNone {
		hasFeature := b.system.HasFeature(path.FeatureRequired)
		if !hasFeature {
			return nil, logical.CodedError(401, "Feature Not Enabled")
		}
	}

	// Build up the data for the route, with the URL taking priority
	// for the fields over the PUT data.
	raw := make(map[string]interface{}, len(path.Fields))
	for k, v := range req.Data {
		raw[k] = v
	}
	for k, v := range captures {
		raw[k] = v
	}

	// Look up the callback for this operation, preferring the
	// path.Operations definition if present.
	var callback OperationFunc

	if path.Operations != nil {
		if op, ok := path.Operations[req.Operation]; ok {
			callback = op.Handler()
		}
	} else {
		callback = path.Callbacks[req.Operation]
	}
	ok := callback != nil

	if !ok {
		if req.Operation == logical.HelpOperation {
			callback = path.helpCallback(b)
			ok = true
		}
	}
	if !ok {
		return nil, logical.ErrUnsupportedOperation
	}

	fd := FieldData{
		Raw:    raw,
		Schema: path.Fields}

	if req.Operation != logical.HelpOperation {
		err := fd.Validate()
		if err != nil {
			return nil, err
		}
	}

	return callback(ctx, req, &fd)
}
885323
func (ls *ListAffinityGroups) ListRequest() (ListCommand, error) {
	if ls == nil {
		return nil, fmt.Errorf("%T cannot be nil", ls)
	}
	return ls, nil
}
727747
func (c Client) MakeRequest(req Request) (Response, error) {
	if req.AcceptableStatusCodes == nil {
		panic("acceptable status codes for this request were not set")
	}

	request, err := c.buildRequest(req)
	if err != nil {
		return Response{}, err
	}

	var resp *http.Response
	transport := buildTransport(c.config.SkipVerifySSL)
	if req.DoNotFollowRedirects {
		resp, err = transport.RoundTrip(request)
	} else {
		client := &http.Client{Transport: transport}
		resp, err = client.Do(request)
	}
	if err != nil {
		return Response{}, newRequestHTTPError(err)
	}
	defer resp.Body.Close()

	responseBody, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return Response{}, newResponseReadError(err)
	}

	return c.handleResponse(req, Response{
		Code:    resp.StatusCode,
		Body:    responseBody,
		Headers: resp.Header,
	})
}
1097908
func (s *SocketServer) handleRequests(closeConn chan error, conn net.Conn, responses chan<- *types.Response) {
	var count int
	var bufReader = bufio.NewReader(conn)
	for {

		var req = &types.Request{}
		err := types.ReadMessage(bufReader, req)
		if err != nil {
			if err == io.EOF {
				closeConn <- err
			} else {
				closeConn <- fmt.Errorf("Error reading message: %v", err.Error())
			}
			return
		}
		s.appMtx.Lock()
		count++
		s.handleRequest(req, responses)
		s.appMtx.Unlock()
	}
}
738984
func (no NetworkOffering) ListRequest() (ListCommand, error) {
	req := &ListNetworkOfferings{
		Availability: no.Availability,
		ID:           no.ID,
		Name:         no.Name,
		State:        no.State,
		TrafficType:  no.TrafficType,
	}

	return req, nil
}
373960
func (r *Router) HandleRequest(ctx *fasthttp.RequestCtx) {
	c := r.pool.Get().(*Context)
	c.init(ctx)
	c.handlers, c.pnames = r.find(string(ctx.Method()), string(ctx.Path()), c.pvalues)
	if err := c.Next(); err != nil {
		r.handleError(c, err)
	}
	r.pool.Put(c)
}