// URLHandler returns a handler setting the request's URL as a field
// to the current context's logger using the passed name as field name.
554167
func URLHandler(name string) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			l := FromContext(r.Context())
			l.SetField(name, r.URL.String())
			next.ServeHTTP(w, r)
		})
	}
}
214608
func (c *Context) APIHandler(builder Builder) http.Handler {
	b := builder
	if b == nil {
		b = PassthroughBuilder
	}

	var title string
	sp := c.spec.Spec()
	if sp != nil && sp.Info != nil && sp.Info.Title != "" {
		title = sp.Info.Title
	}

	redocOpts := RedocOpts{
		BasePath: c.BasePath(),
		Title:    title,
	}

	return Spec("", c.spec.Raw(), Redoc(redocOpts, c.RoutesHandler(b)))
}
1111846
func (c *Context) RoutesHandler(builder Builder) http.Handler {
	b := builder
	if b == nil {
		b = PassthroughBuilder
	}
	return NewRouter(c, b(NewOperationExecutor(c)))
}
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)
	}
}
598986
func RemoteAddrHandler(fieldKey string) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
				log := zerolog.Ctx(r.Context())
				log.UpdateContext(func(c zerolog.Context) zerolog.Context {
					return c.Str(fieldKey, host)
				})
			}
			next.ServeHTTP(w, r)
		})
	}
}
1179022
func httpParamsHandler(chain alice.Chain, handler Route) httprouter.Handle {
	h := wrapper(chain, handler)
	return func(w http.ResponseWriter, req *http.Request, params httprouter.Params) {
		req = req.WithContext(context.WithValue(req.Context(), ParamsKey, params))
		h.ServeHTTP(w, req)
	}
}
555783
func GetHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
	defer r.Body.Close()
	vars := mux.Vars(r)
	return getHandler(ctx, w, r, vars)
}
1303186
func (app *Application) handler(ctx *Context) {
	for prefix, staticPathSlice := range app.staticRouter {
		if strings.HasPrefix(ctx.Request.URL.Path, prefix) {
			for _, staticPath := range staticPathSlice {
				filePath := path.Join(staticPath, ctx.Request.URL.Path[len(prefix):])
				fileInfo, err := os.Stat(filePath)
				if err == nil && !fileInfo.IsDir() {
					staticHandler(ctx, filePath)
					return
				}
			}
		}
	}

	handler, params, err := app.router.FindRoute(ctx.Request.Method, ctx.Request.URL.Path)
	if err != nil {
		app.handleError(ctx, 404)
	} else {
		ctx.Params = params
		handler(ctx)
	}
	ctx.IsSent = true
}
150070
func (h *Handler) ContextHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	// get query
	opts := NewRequestOptions(r)

	// execute graphql query
	params := graphql.Params{
		Schema:         *h.Schema,
		RequestString:  opts.Query,
		VariableValues: opts.Variables,
		OperationName:  opts.OperationName,
		Context:        ctx,
	}
	if h.rootObjectFn != nil {
		params.RootObject = h.rootObjectFn(ctx, r)
	}
	result := graphql.Do(params)

	if formatErrorFn := h.formatErrorFn; formatErrorFn != nil && len(result.Errors) > 0 {
		formatted := make([]gqlerrors.FormattedError, len(result.Errors))
		for i, formattedError := range result.Errors {
			formatted[i] = formatErrorFn(formattedError.OriginalError())
		}
		result.Errors = formatted
	}

	if h.graphiql {
		acceptHeader := r.Header.Get("Accept")
		_, raw := r.URL.Query()["raw"]
		if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
			renderGraphiQL(w, params)
			return
		}
	}

	if h.playground {
		acceptHeader := r.Header.Get("Accept")
		_, raw := r.URL.Query()["raw"]
		if !raw && !strings.Contains(acceptHeader, "application/json") && strings.Contains(acceptHeader, "text/html") {
			renderPlayground(w, r)
			return
		}
	}

	// use proper JSON Header
	w.Header().Add("Content-Type", "application/json; charset=utf-8")

	var buff []byte
	if h.pretty {
		w.WriteHeader(http.StatusOK)
		buff, _ = json.MarshalIndent(result, "", "\t")

		w.Write(buff)
	} else {
		w.WriteHeader(http.StatusOK)
		buff, _ = json.Marshal(result)

		w.Write(buff)
	}

	if h.resultCallbackFn != nil {
		h.resultCallbackFn(ctx, &params, result, buff)
	}
}
777775
func NewHandler(prefix string, opts Options, handleFunc func(Session)) http.Handler {
	return newHandler(prefix, opts, handleFunc)
}
84121
func UpHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {
		updater.Update(nil)
	} else {
		w.WriteHeader(http.StatusNotFound)
	}
}
1214405
func NewHandler() *Handler {
	h := &Handler{
		router: httprouter.New(),
		Logger: log15.New(),
	}
	h.router.Handler("GET", status.Path, status.Handler(h.healthStatus))
	h.router.GET("/status", h.handleGetStatus)
	h.router.GET("/backup", h.handleGetBackup)
	h.router.POST("/stop", h.handlePostStop)
	return h
}
1344748
func (router *Router) FindHandler(req *http.Request) (http.HandlerFunc, bool) {

	// Ask child first
	for _, child := range router.subrouters {
		handler, ok := child.FindHandler(req)
		if ok && handler != nil {
			return func(w http.ResponseWriter, req *http.Request) {
				child.handleFilteredFunc(handler, w, req)
			}, ok
		}
	}

	// Ask subroute
	if handlers, ok := router.routes[MethodAny]; ok {
		for key, handler := range handlers {
			if strings.HasPrefix(req.URL.Path, key) {
				// Match!!
				rest := strings.Replace(req.URL.Path, key, "", -1)
				if !strings.HasPrefix(rest, "/") {
					rest = "/" + rest
				}
				return handler, true
			}
		}
	}

	// Ask normal routes
	if handlers, ok := router.routes[HTTPMethod(req.Method)]; ok {
		if handler, ok := handlers[req.URL.Path]; ok {
			return handler, true
		}
	}

	// Ask regex routes
	if handlers, ok := router.regexps[HTTPMethod(req.Method)]; ok {
		for exp, handler := range handlers {
			if exp.MatchString(req.URL.Path) {
				matched := exp.FindAllStringSubmatch(req.URL.Path, -1)
				if req.Form == nil {
					req.Form = url.Values{}
				}
				for i, name := range exp.SubexpNames() {
					req.Form.Add(name, matched[0][i])
				}
				return handler, true
			}
		}
	}
	return nil, false
}
1169776
func PathsHandler(w http.ResponseWriter, r *http.Request) {
	var (
		err error
		id  int64
	)
	val := r.Context().Value(ctxDBKey)
	if val == nil {
		httpError(w, r, http.StatusInternalServerError,
			fmt.Sprintf("Could not find database handler in request context"))
		return
	}
	db := val.(*pg.DB)

	if r.FormValue("id") != "" {
		id, err = strconv.ParseInt(r.FormValue("id"), 10, 64)
		if err != nil {
			httpError(w, r, http.StatusBadRequest,
				fmt.Sprintf("Could not parse certificate id: %v", err))
			return
		}
	} else if r.FormValue("sha256") != "" {
		id, err = db.GetCertIDBySHA256Fingerprint(r.FormValue("sha256"))
		if err != nil {
			httpError(w, r, http.StatusInternalServerError,
				fmt.Sprintf("Could not retrieve certificate: %v", err))
			return
		}
	} else {
		httpError(w, r, http.StatusBadRequest, "Certificate ID or SHA256 are missing")
		return
	}
	cert, err := db.GetCertByID(id)
	if err != nil {
		httpError(w, r, http.StatusInternalServerError,
			fmt.Sprintf("Could not retrieved stored certificate from database: %v", err))
		return
	}
	paths, err := db.GetCertPaths(cert)
	if err != nil {
		httpError(w, r, http.StatusInternalServerError,
			fmt.Sprintf("Failed to retrieve certificate paths from database: %v", err))
		return
	}
	pathsJson, err := json.Marshal(paths)
	if err != nil {
		httpError(w, r, http.StatusInternalServerError,
			fmt.Sprintf("Could not convert certificate paths to JSON: %v", err))
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	w.Write(pathsJson)
	return
}
781507
func PathHandler(t *testing.T, reqPath string, respStatus int, respBody string) http.Handler {
	var meth, path string

	s := strings.SplitN(reqPath, " ", 2)
	if len(s) == 1 {
		t.Fatal("reqPath must be of the form `<METHOD> <PATH>`")
	}

	meth = s[0]
	path = s[1]

	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if meth == r.Method && path == r.URL.Path {
			w.WriteHeader(respStatus)
			w.Write([]byte(respBody))
		} else {
			w.WriteHeader(http.StatusNotFound)
			t.Errorf("http request => %s %s; want %s %s", r.Method, r.URL.Path, meth, path)
		}
	})
}
393889
func WrapRouteHandler(r http.Handler) RHandler {
	return func(res http.ResponseWriter, req *http.Request, _ Collector) {
		r.ServeHTTP(res, req)
	}
}
1258514
func (s *Service) RegisterHandler(name string, handler Handler) {
	s.handlers[name] = handler
}