// StatusHandler returns a proper response for provided status code
336555
func StatusHandler(w http.ResponseWriter, r *http.Request) {
	code, _ := strconv.Atoi(mux.Vars(r)["code"])

	statusWritten := false
	switch code {
	case http.StatusMovedPermanently,
		http.StatusFound,
		http.StatusSeeOther,
		http.StatusUseProxy,
		http.StatusTemporaryRedirect:
		w.Header().Set("Location", "/redirect/1")
	case http.StatusUnauthorized: // 401
		w.Header().Set("WWW-Authenticate", `Basic realm="Fake Realm"`)
	case http.StatusPaymentRequired: // 402
		w.WriteHeader(code)
		statusWritten = true
		io.WriteString(w, "Fuck you, pay me!")
		w.Header().Set("x-more-info", "http://vimeo.com/22053820")
	case http.StatusNotAcceptable: // 406
		w.WriteHeader(code)
		statusWritten = true
		io.WriteString(w, `{"message": "Client did not request a supported media type.", "accept": ["image/webp", "image/svg+xml", "image/jpeg", "image/png", "image/*"]}`)
	case http.StatusTeapot:
		w.WriteHeader(code)
		statusWritten = true
		w.Header().Set("x-more-info", "http://tools.ietf.org/html/rfc2324")
		io.WriteString(w, `
    -=[ teapot ]=-

       _...._
     .'  _ _ '.
    | ."  ^  ". _,
    \_;'"---"'|//
      |       ;/
      \_     _/
        '"""'
`)
	}
	if !statusWritten {
		w.WriteHeader(code)
	}
}
999438
func (p *ProxyWriter) StatusCode() int {
	if p.code == 0 {
		// per contract standard lib will set this to http.StatusOK if not set
		// by user, here we avoid the confusion by mirroring this logic
		return http.StatusOK
	}
	return p.code
}
1018612
func (r *httpJSONResponseElement) StatusCode() int {
	if r.statusCode == nil {
		statusCode := 200
		// Look for "error" field
		if errorFieldJSON, found := r.bodyObject["error"]; found {
			var hasError bool
			if err := json.Unmarshal(*errorFieldJSON, &hasError); err == nil && hasError {
				// We have an error, look for code field
				statusCode = 500
				if codeFieldJSON, found := r.bodyObject["code"]; found {
					var code int
					if err := json.Unmarshal(*codeFieldJSON, &code); err == nil {
						statusCode = code
					}
				}
			}
		}
		r.statusCode = &statusCode
	}
	return *r.statusCode
}
998103
func (b *Base) ErrorHandler(err error, m message.Composer) {
	b.mutex.RLock()
	defer b.mutex.RUnlock()

	b.errHandler(err, m)
}
706144
func (r *Registry) HTTPHandler() http.Handler {
	opts := promhttp.HandlerOpts{
		ErrorLog: promLogger{r: r},
		// TODO(mr): decide if we want to set MaxRequestsInFlight or Timeout.
	}
	return promhttp.HandlerFor(r.Registry, opts)
}
540688
func (r *Router) HTTPSHandler(handler http.Handler, config *tls.Config) {
	r.httpsHandler = handler
	r.httpsTLSConfig = config
}
1342031
func (res *Resource) postHandler(w http.ResponseWriter, r *http.Request, storage store.Save) {
	parsedObject, parseErr := jsh.ParseObject(r)
	if parseErr != nil && reflect.ValueOf(parseErr).IsNil() == false {
		SendHandler(w, r, parseErr)
		return
	}

	object, err := storage(r.Context(), parsedObject)
	if err != nil && reflect.ValueOf(err).IsNil() == false {
		SendHandler(w, r, err)
		return
	}

	SendHandler(w, r, object)
}
1355795
func ErrorResponseHandler(request *restful.Request, response *restful.Response, origin error, err *ErrorResponse) {
	fields := log.Fields{
		"Internal":    err.Err[0].InternalError,
		"Description": err.Err[0].Msg,
		"Context":     err.Err[0].Context,
		"URL":         request.Request.URL.String(),
		"Method":      request.Request.Method,
	}

	for k, vs := range request.Request.Form {
		var out string
		for i, v := range vs {
			if i > 0 {
				out += ","
			}
			out += v
		}
		fields[k] = out
	}
	log.WithFields(fields).Error(origin)

	if response != nil {
		response.WriteHeaderAndEntity(err.Err[0].Code, err)
	}
}
996416
func StatusCode(err error) int {
	if err == nil {
		return http.StatusOK
	}
	if val, ok := errors.TagValueIn(statusCodeTagKey, err); ok {
		return val.(int)
	}
	return 0
}
987068
func (l *lockRESTServer) LockHandler(w http.ResponseWriter, r *http.Request) {
	if !l.IsValid(w, r) {
		l.writeErrorResponse(w, errors.New("Invalid request"))
		return
	}

	ctx := newContext(r, w, "Lock")

	var lockArgs dsync.LockArgs
	if r.ContentLength < 0 {
		l.writeErrorResponse(w, errInvalidArgument)
		return
	}

	err := gob.NewDecoder(r.Body).Decode(&lockArgs)
	if err != nil {
		l.writeErrorResponse(w, err)
		return
	}

	success, err := l.ll.Lock(lockArgs)
	if err != nil {
		l.writeErrorResponse(w, err)
		return
	}
	resp := lockResponse{Success: success}
	logger.LogIf(ctx, gob.NewEncoder(w).Encode(resp))
	w.(http.Flusher).Flush()
}
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)))
}
377399
func CheckErrorStatus(code int, res *http.Response) error {
	err := CheckError(res)
	if err != nil {
		return err
	}

	if res.StatusCode != code {
		return fmt.Errorf("unexpected status code: %s", res.Status)
	}

	return nil
}
1028692
func HTTPHandler(c alice.Chain, fs http.Handler) http.Handler {
	return c.Then(fs)
}
768480
func (r *Response) Status(code int) JResponseWriter {
	r.code = code
	return r
}
736189
func (s *SidecarApi) stateHandler(response http.ResponseWriter, req *http.Request, params map[string]string) {
	defer req.Body.Close()

	s.state.RLock()
	defer s.state.RUnlock()

	if params["extension"] != "json" {
		sendJsonError(response, 404, "Not Found - Invalid content type extension")
		return
	}

	response.Header().Set("Content-Type", "application/json")
	response.Header().Set("Access-Control-Allow-Origin", "*")
	response.Header().Set("Access-Control-Allow-Methods", "GET")
	response.Write(s.state.Encode())
	return
}
26549
func CommandHandler(commandHandler eh.CommandHandler, commandType eh.CommandType) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.Method != "POST" {
			http.Error(w, "unsuported method: "+r.Method, http.StatusMethodNotAllowed)
			return
		}

		cmd, err := eh.CreateCommand(commandType)
		if err != nil {
			http.Error(w, "could not create command: "+err.Error(), http.StatusBadRequest)
			return
		}

		b, err := ioutil.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "could not read command: "+err.Error(), http.StatusBadRequest)
			return
		}
		if err := json.Unmarshal(b, &cmd); err != nil {
			http.Error(w, "could not decode command: "+err.Error(), http.StatusBadRequest)
			return
		}

		// NOTE: Use a new context when handling, else it will be cancelled with
		// the HTTP request which will cause projectors etc to fail if they run
		// async in goroutines past the request.
		ctx := context.Background()
		if err := commandHandler.HandleCommand(ctx, cmd); err != nil {
			http.Error(w, "could not handle command: "+err.Error(), http.StatusBadRequest)
			return
		}

		w.WriteHeader(http.StatusOK)
	})
}
897356
func (mh *MethodHandler) StatusCodes(codes ...int) *MethodHandler {
	if mh.statusCodes == nil {
		mh.statusCodes = make([]int, 0)
	}
	mh.statusCodes = append(mh.statusCodes, codes...)
	return mh
}