// Creates a closure function that is used as an http handler that allows
// users to publish events (what this example is calling a user action event)
169824
func getUserActionHandler(manager *golongpoll.LongpollManager) func(w http.ResponseWriter, r *http.Request) {
	// Creates closure that captures the LongpollManager
	return func(w http.ResponseWriter, r *http.Request) {
		user := r.URL.Query().Get("user")
		action := r.URL.Query().Get("action")
		public := r.URL.Query().Get("public")
		// Perform validation on url query params:
		if len(user) == 0 || len(action) == 0 {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte("Missing required URL param."))
			return
		}
		if user != "larry" && user != "moe" && user != "curly" {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte("Not a user."))
			return
		}
		if len(public) > 0 && public != "true" {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte("Optional param 'public' must be 'true' if present."))
			return
		}
		// convert string arg to bool
		isPublic := false
		if public == "true" {
			isPublic = true
		}
		actionEvent := UserAction{User: user, Action: action, IsPublic: isPublic}
		// Publish on public subscription channel if the action is public.
		// Everyone can see this event.
		if isPublic {
			manager.Publish("public_actions", actionEvent)
		}
		// Publish on user's private channel regardless
		// Only the user that called this will see the event.
		manager.Publish(user+"_actions", actionEvent)
	}
}
94677
func MakeStdHandler(fn StdHandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// ensure that neither proxies nor browsers cache http traffic
		SetNoCacheHeaders(w.Header())

		out, err := fn(w, r)
		if err != nil {
			trace.WriteError(w, err)
			return
		}
		if out != nil {
			roundtrip.ReplyJSON(w, http.StatusOK, out)
		}
	}
}
1255618
func Wrap(handler Handler) gin.HandlerFunc {
	return func(c *gin.Context) {
		inj, exist := Get(c)
		if !exist {
			c.AbortWithError(http.StatusServiceUnavailable, ErrorInjectorNotFound.New(nil))
			return
		}

		if _, err := injectutil.Invoke(inj, handler); err != nil {
			c.AbortWithError(http.StatusNotFound, err)
		}
	}
}
260617
func _() {
	var _ Event = (*Absolute)(nil)        // assert *Absolute implements Event
	var _ Event = (*FAbsolute)(nil)       // assert *FAbsolute implements Event
	var _ Event = (*Gauge)(nil)           // assert *Gauge implements Event
	var _ Event = (*FGauge)(nil)          // assert *FGauge implements Event
	var _ Event = (*GaugeDelta)(nil)      // assert *GaugeDelta implements Event
	var _ Event = (*FGaugeDelta)(nil)     // assert *FGaugeDelta implements Event
	var _ Event = (*Increment)(nil)       // assert *Increment implements Event
	var _ Event = (*PrecisionTiming)(nil) // assert *PrecisionTiming implements Event
	var _ Event = (*Timing)(nil)          // assert *Timing implements Event
	var _ Event = (*Total)(nil)           // assert *Total implements Event
}
75340
func Handler(h StatusHandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		status, response := h(w, r)
		w.WriteHeader(status)
		if response == nil {
			return
		}

		Responder(w, r, response)
	}
}
923249
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	filters := r.URL.Query()["collect[]"]
	log.Debugln("collect query:", filters)

	if len(filters) == 0 {
		// No filters, use the prepared unfiltered handler.
		h.unfilteredHandler.ServeHTTP(w, r)
		return
	}
	// To serve filtered metrics, we create a filtering handler on the fly.
	filteredHandler, err := h.innerHandler(filters...)
	if err != nil {
		log.Warnln("Couldn't create filtered metrics handler:", err)
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(fmt.Sprintf("Couldn't create filtered metrics handler: %s", err)))
		return
	}
	filteredHandler.ServeHTTP(w, r)
}
772621
func createEvent(action string) *Event {
	return &Event{
		ID:        uuid.Generate().String(),
		Timestamp: time.Now(),
		Action:    action,
	}
}
761947
func (f *httpHandlerFunc) Serve(ctx context.Context, in io.Reader, out io.Writer) {
	reqURL := "http://localhost/invoke"
	reqMethod := "POST"
	if ctx, ok := GetContext(ctx).(HTTPContext); ok {
		reqURL = ctx.RequestURL()
		reqMethod = ctx.RequestMethod()
	}

	req, err := http.NewRequest(reqMethod, reqURL, in)
	if err != nil {
		panic("cannot re-create request from context")
	}

	req.Header = GetContext(ctx).Header()
	req = req.WithContext(ctx)

	rw, ok := out.(http.ResponseWriter)
	if !ok {
		panic("output is not a response writer, this was poorly planned please yell at me")
	}

	f.ServeHTTP(rw, req)
}
999450
func (ra *RemoteAddr) HandlerFunc(w http.ResponseWriter, r *http.Request) {
	ra.handleActualRequest(w, r)
}
414449
func Handler(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		rc := &responseCapture{w, 0}

		s := time.Now()
		h.ServeHTTP(rc, req)
		e := time.Now()
		d := e.Sub(s)

		data := Data{
			"start":    s,
			"end":      e,
			"duration": d,
			"status":   rc.statusCode,
			"method":   req.Method,
			"path":     req.URL.Path,
		}
		if len(req.URL.RawQuery) > 0 {
			data["query"] = req.URL.Query()
		}
		Event("request", GetRequestID(req), data)
	})
}
853418
func (o *MultiAuthExampleAPI) HandlerFor(method, path string) (http.Handler, bool) {
	if o.handlers == nil {
		return nil, false
	}
	um := strings.ToUpper(method)
	if _, ok := o.handlers[um]; !ok {
		return nil, false
	}
	if path == "/" {
		path = ""
	}
	h, ok := o.handlers[um][path]
	return h, ok
}
842040
func eventHandler(w http.ResponseWriter, r *http.Request) {
	if r.Body != nil {
		defer r.Body.Close()
	}

	ctx := r.Context()

	switch r.Method {
	// Get all events
	case http.MethodGet:
		events, err := getEvents(Configuration.Service.ReadMaxLimit)
		if err != nil {
			LoggingClient.Error(err.Error())
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		encode(events, w)
		break
		// Post a new event
	case http.MethodPost:
		contentType := r.Header.Get(clients.ContentType)
		if contentType == clients.ContentTypeCBOR {
			errMsg := "CBOR payload is not yet supported"
			http.Error(w, errMsg, http.StatusNotImplemented)
			LoggingClient.Error(errMsg)

			return
		}

		var e models.Event
		dec := json.NewDecoder(r.Body)
		err := dec.Decode(&e)

		// Problem Decoding Event
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			LoggingClient.Error("Error decoding event: " + err.Error())
			return
		}

		LoggingClient.Info("Posting Event: " + e.String())

		newId, err := addNewEvent(e, ctx)
		if err != nil {
			switch t := err.(type) {
			case *errors.ErrValueDescriptorNotFound:
				http.Error(w, t.Error(), http.StatusBadRequest)
			case *errors.ErrValueDescriptorInvalid:
				http.Error(w, t.Error(), http.StatusBadRequest)
			default:
				http.Error(w, t.Error(), http.StatusInternalServerError)
			}
			LoggingClient.Error(err.Error())
			return
		}

		w.WriteHeader(http.StatusOK)
		w.Write([]byte(newId))

		break
		// Do not update the readings
	case http.MethodPut:
		contentType := r.Header.Get(clients.ContentType)
		if contentType == clients.ContentTypeCBOR {
			errMsg := "CBOR payload is not yet supported"
			http.Error(w, errMsg, http.StatusNotImplemented)
			LoggingClient.Error(errMsg)

			return
		}

		var from models.Event
		dec := json.NewDecoder(r.Body)
		err := dec.Decode(&from)

		// Problem decoding event
		if err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			LoggingClient.Error("Error decoding the event: " + err.Error())
			return
		}

		LoggingClient.Info("Updating event: " + from.ID)
		err = updateEvent(from, ctx)
		if err != nil {
			switch t := err.(type) {
			case *errors.ErrEventNotFound:
				http.Error(w, t.Error(), http.StatusNotFound)
			default:
				http.Error(w, t.Error(), http.StatusInternalServerError)
			}
			LoggingClient.Error(err.Error())
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		w.Write([]byte("true"))
	}
}
1141203
func makeHandler(n *core.IpfsNode, l net.Listener, options ...ServeOption) (http.Handler, error) {
	topMux := http.NewServeMux()
	mux := topMux
	for _, option := range options {
		var err error
		mux, err = option(n, l, mux)
		if err != nil {
			return nil, err
		}
	}
	return topMux, nil
}
154152
func (eh userNoteUpdateEventHandler) Handle(s *Session, i interface{}) {
	if t, ok := i.(*UserNoteUpdate); ok {
		eh(s, t)
	}
}
811596
func (m *Method) PostHandle(handler Handler) *Method {
	m.postHandlers = append(m.postHandlers, handler)
	return m
}
941263
func NewEventHandler(eventHandler eh.EventHandler) *EventHandler {
	h := &EventHandler{
		EventHandler: eventHandler,
		eventsCh:     make(chan data),
		errCh:        make(chan error, 1),
	}

	go h.run()

	return h
}
1175270
func MakeHTTPHandler(s Service, logger log.Logger) http.Handler {
	r := mux.NewRouter()
	e := MakeServerEndpoints(s)
	options := []httptransport.ServerOption{
		httptransport.ServerErrorHandler(transport.NewLogErrorHandler(logger)),
		httptransport.ServerErrorEncoder(encodeError),
	}

	// POST    /profiles/                          adds another profile
	// GET     /profiles/:id                       retrieves the given profile by id
	// PUT     /profiles/:id                       post updated profile information about the profile
	// PATCH   /profiles/:id                       partial updated profile information
	// DELETE  /profiles/:id                       remove the given profile
	// GET     /profiles/:id/addresses/            retrieve addresses associated with the profile
	// GET     /profiles/:id/addresses/:addressID  retrieve a particular profile address
	// POST    /profiles/:id/addresses/            add a new address
	// DELETE  /profiles/:id/addresses/:addressID  remove an address

	r.Methods("POST").Path("/profiles/").Handler(httptransport.NewServer(
		e.PostProfileEndpoint,
		decodePostProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}").Handler(httptransport.NewServer(
		e.GetProfileEndpoint,
		decodeGetProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PUT").Path("/profiles/{id}").Handler(httptransport.NewServer(
		e.PutProfileEndpoint,
		decodePutProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("PATCH").Path("/profiles/{id}").Handler(httptransport.NewServer(
		e.PatchProfileEndpoint,
		decodePatchProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/profiles/{id}").Handler(httptransport.NewServer(
		e.DeleteProfileEndpoint,
		decodeDeleteProfileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
		e.GetAddressesEndpoint,
		decodeGetAddressesRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
		e.GetAddressEndpoint,
		decodeGetAddressRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/profiles/{id}/addresses/").Handler(httptransport.NewServer(
		e.PostAddressEndpoint,
		decodePostAddressRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/profiles/{id}/addresses/{addressID}").Handler(httptransport.NewServer(
		e.DeleteAddressEndpoint,
		decodeDeleteAddressRequest,
		encodeResponse,
		options...,
	))
	return r
}