// HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).
500111
func (c *Characteristic) HandleWriteFunc(f func(r Request, data []byte) (status byte)) {
	c.HandleWrite(WriteHandlerFunc(f))
}
789148
func NewWriteHandler(writer storage.PointsWriter) *WriteHandler {
	h := &WriteHandler{
		Router:       NewRouter(),
		Logger:       zap.NewNop(),
		PointsWriter: writer,
	}

	h.HandlerFunc("POST", writePath, h.handleWrite)
	return h
}
184291
func (b *databaseBackend) connectionWriteHandler() framework.OperationFunc {
	return func(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
		verifyConnection := data.Get("verify_connection").(bool)

		name := data.Get("name").(string)
		if name == "" {
			return logical.ErrorResponse(respErrEmptyName), nil
		}

		// Baseline
		config := &DatabaseConfig{}

		entry, err := req.Storage.Get(ctx, fmt.Sprintf("config/%s", name))
		if err != nil {
			return nil, errors.New("failed to read connection configuration")
		}
		if entry != nil {
			if err := entry.DecodeJSON(config); err != nil {
				return nil, err
			}
		}

		if pluginNameRaw, ok := data.GetOk("plugin_name"); ok {
			config.PluginName = pluginNameRaw.(string)
		} else if req.Operation == logical.CreateOperation {
			config.PluginName = data.Get("plugin_name").(string)
		}
		if config.PluginName == "" {
			return logical.ErrorResponse(respErrEmptyPluginName), nil
		}

		if allowedRolesRaw, ok := data.GetOk("allowed_roles"); ok {
			config.AllowedRoles = allowedRolesRaw.([]string)
		} else if req.Operation == logical.CreateOperation {
			config.AllowedRoles = data.Get("allowed_roles").([]string)
		}

		if rootRotationStatementsRaw, ok := data.GetOk("root_rotation_statements"); ok {
			config.RootCredentialsRotateStatements = rootRotationStatementsRaw.([]string)
		} else if req.Operation == logical.CreateOperation {
			config.RootCredentialsRotateStatements = data.Get("root_rotation_statements").([]string)
		}

		// Remove these entries from the data before we store it keyed under
		// ConnectionDetails.
		delete(data.Raw, "name")
		delete(data.Raw, "plugin_name")
		delete(data.Raw, "allowed_roles")
		delete(data.Raw, "verify_connection")
		delete(data.Raw, "root_rotation_statements")

		// Create a database plugin and initialize it.
		db, err := dbplugin.PluginFactory(ctx, config.PluginName, b.System(), b.logger)
		if err != nil {
			return logical.ErrorResponse(fmt.Sprintf("error creating database object: %s", err)), nil
		}

		// If this is an update, take any new values, overwrite what was there
		// before, and pass that in as the "new" set of values to the plugin,
		// then save what results
		if req.Operation == logical.CreateOperation {
			config.ConnectionDetails = data.Raw
		} else {
			if config.ConnectionDetails == nil {
				config.ConnectionDetails = make(map[string]interface{})
			}
			for k, v := range data.Raw {
				config.ConnectionDetails[k] = v
			}
		}

		config.ConnectionDetails, err = db.Init(ctx, config.ConnectionDetails, verifyConnection)
		if err != nil {
			db.Close()
			return logical.ErrorResponse(fmt.Sprintf("error creating database object: %s", err)), nil
		}

		b.Lock()
		defer b.Unlock()

		// Close and remove the old connection
		b.clearConnection(name)

		id, err := uuid.GenerateUUID()
		if err != nil {
			return nil, err
		}

		b.connections[name] = &dbPluginInstance{
			Database: db,
			name:     name,
			id:       id,
		}

		// Store it
		entry, err = logical.StorageEntryJSON(fmt.Sprintf("config/%s", name), config)
		if err != nil {
			return nil, err
		}
		if err := req.Storage.Put(ctx, entry); err != nil {
			return nil, err
		}

		resp := &logical.Response{}

		// This is a simple test to to check for passwords in the connection_url paramater. If one exists,
		// warn the user to use templated url string
		if connURLRaw, ok := config.ConnectionDetails["connection_url"]; ok {
			if connURL, err := url.Parse(connURLRaw.(string)); err == nil {
				if _, ok := connURL.User.Password(); ok {
					resp.AddWarning("Password found in connection_url, use a templated url to enable root rotation and prevent read access to password information.")
				}
			}
		}

		return resp, nil
	}
}
766956
func (s *staticPageHandler) Getfunc(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(s.returnCode)
	w.Write(s.pageContents)
}
64444
func (h CommandHandlerFunc) HandleCommand(ctx context.Context, cmd Command) error {
	return h(ctx, cmd)
}
1313043
func Errors() HandlerFunc {
	return func(ctx *Context) {
		switch res := ctx.Result.(type) {
		case AbortError:
			ctx.WriteHeader(res.Code())
			ctx.WriteString(res.Error())
		case error:
			ctx.WriteHeader(http.StatusInternalServerError)
			ctx.WriteString(res.Error())
		default:
			ctx.WriteHeader(http.StatusInternalServerError)
			ctx.WriteString(http.StatusText(http.StatusInternalServerError))
		}
	}
}
215368
func (b *SystemBackend) handleTuneWriteCommon(ctx context.Context, path string, data *framework.FieldData) (*logical.Response, error) {
	repState := b.Core.ReplicationState()

	path = sanitizeMountPath(path)

	// Prevent protected paths from being changed
	for _, p := range untunableMounts {
		if strings.HasPrefix(path, p) {
			b.Backend.Logger().Error("cannot tune this mount", "path", path)
			return handleError(fmt.Errorf("cannot tune %q", path))
		}
	}

	mountEntry := b.Core.router.MatchingMountEntry(ctx, path)
	if mountEntry == nil {
		b.Backend.Logger().Error("tune failed", "error", "no mount entry found", "path", path)
		return handleError(fmt.Errorf("tune of path %q failed: no mount entry found", path))
	}
	if mountEntry != nil && !mountEntry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) {
		return nil, logical.ErrReadOnly
	}

	var lock *sync.RWMutex
	switch {
	case strings.HasPrefix(path, credentialRoutePrefix):
		lock = &b.Core.authLock
	default:
		lock = &b.Core.mountsLock
	}

	lock.Lock()
	defer lock.Unlock()

	// Check again after grabbing the lock
	mountEntry = b.Core.router.MatchingMountEntry(ctx, path)
	if mountEntry == nil {
		b.Backend.Logger().Error("tune failed", "error", "no mount entry found", "path", path)
		return handleError(fmt.Errorf("tune of path %q failed: no mount entry found", path))
	}
	if mountEntry != nil && !mountEntry.Local && repState.HasState(consts.ReplicationPerformanceSecondary) {
		return nil, logical.ErrReadOnly
	}

	// Timing configuration parameters
	{
		var newDefault, newMax time.Duration
		defTTL := data.Get("default_lease_ttl").(string)
		switch defTTL {
		case "":
			newDefault = mountEntry.Config.DefaultLeaseTTL
		case "system":
			newDefault = time.Duration(0)
		default:
			tmpDef, err := parseutil.ParseDurationSecond(defTTL)
			if err != nil {
				return handleError(err)
			}
			newDefault = tmpDef
		}

		maxTTL := data.Get("max_lease_ttl").(string)
		switch maxTTL {
		case "":
			newMax = mountEntry.Config.MaxLeaseTTL
		case "system":
			newMax = time.Duration(0)
		default:
			tmpMax, err := parseutil.ParseDurationSecond(maxTTL)
			if err != nil {
				return handleError(err)
			}
			newMax = tmpMax
		}

		if newDefault != mountEntry.Config.DefaultLeaseTTL ||
			newMax != mountEntry.Config.MaxLeaseTTL {

			if err := b.tuneMountTTLs(ctx, path, mountEntry, newDefault, newMax); err != nil {
				b.Backend.Logger().Error("tuning failed", "path", path, "error", err)
				return handleError(err)
			}
		}
	}

	if rawVal, ok := data.GetOk("description"); ok {
		description := rawVal.(string)

		oldDesc := mountEntry.Description
		mountEntry.Description = description

		// Update the mount table
		var err error
		switch {
		case strings.HasPrefix(path, "auth/"):
			err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local)
		default:
			err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local)
		}
		if err != nil {
			mountEntry.Description = oldDesc
			return handleError(err)
		}
		if b.Core.logger.IsInfo() {
			b.Core.logger.Info("mount tuning of description successful", "path", path, "description", description)
		}
	}

	if rawVal, ok := data.GetOk("audit_non_hmac_request_keys"); ok {
		auditNonHMACRequestKeys := rawVal.([]string)

		oldVal := mountEntry.Config.AuditNonHMACRequestKeys
		mountEntry.Config.AuditNonHMACRequestKeys = auditNonHMACRequestKeys

		// Update the mount table
		var err error
		switch {
		case strings.HasPrefix(path, "auth/"):
			err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local)
		default:
			err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local)
		}
		if err != nil {
			mountEntry.Config.AuditNonHMACRequestKeys = oldVal
			return handleError(err)
		}

		mountEntry.SyncCache()

		if b.Core.logger.IsInfo() {
			b.Core.logger.Info("mount tuning of audit_non_hmac_request_keys successful", "path", path)
		}
	}

	if rawVal, ok := data.GetOk("audit_non_hmac_response_keys"); ok {
		auditNonHMACResponseKeys := rawVal.([]string)

		oldVal := mountEntry.Config.AuditNonHMACResponseKeys
		mountEntry.Config.AuditNonHMACResponseKeys = auditNonHMACResponseKeys

		// Update the mount table
		var err error
		switch {
		case strings.HasPrefix(path, "auth/"):
			err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local)
		default:
			err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local)
		}
		if err != nil {
			mountEntry.Config.AuditNonHMACResponseKeys = oldVal
			return handleError(err)
		}

		mountEntry.SyncCache()

		if b.Core.logger.IsInfo() {
			b.Core.logger.Info("mount tuning of audit_non_hmac_response_keys successful", "path", path)
		}
	}

	if rawVal, ok := data.GetOk("listing_visibility"); ok {
		lvString := rawVal.(string)
		listingVisibility := ListingVisibilityType(lvString)

		if err := checkListingVisibility(listingVisibility); err != nil {
			return logical.ErrorResponse(fmt.Sprintf("invalid listing_visibility %s", listingVisibility)), nil
		}

		oldVal := mountEntry.Config.ListingVisibility
		mountEntry.Config.ListingVisibility = listingVisibility

		// Update the mount table
		var err error
		switch {
		case strings.HasPrefix(path, "auth/"):
			err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local)
		default:
			err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local)
		}
		if err != nil {
			mountEntry.Config.ListingVisibility = oldVal
			return handleError(err)
		}

		if b.Core.logger.IsInfo() {
			b.Core.logger.Info("mount tuning of listing_visibility successful", "path", path)
		}
	}

	if rawVal, ok := data.GetOk("token_type"); ok {
		if !strings.HasPrefix(path, "auth/") {
			return logical.ErrorResponse(fmt.Sprintf("'token_type' can only be modified on auth mounts")), logical.ErrInvalidRequest
		}
		if mountEntry.Type == "token" || mountEntry.Type == "ns_token" {
			return logical.ErrorResponse(fmt.Sprintf("'token_type' cannot be set for 'token' or 'ns_token' auth mounts")), logical.ErrInvalidRequest
		}

		tokenType := logical.TokenTypeDefaultService
		ttString := rawVal.(string)

		switch ttString {
		case "", "default-service":
		case "default-batch":
			tokenType = logical.TokenTypeDefaultBatch
		case "service":
			tokenType = logical.TokenTypeService
		case "batch":
			tokenType = logical.TokenTypeBatch
		default:
			return logical.ErrorResponse(fmt.Sprintf(
				"invalid value for 'token_type'")), logical.ErrInvalidRequest
		}

		oldVal := mountEntry.Config.TokenType
		mountEntry.Config.TokenType = tokenType

		// Update the mount table
		if err := b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local); err != nil {
			mountEntry.Config.TokenType = oldVal
			return handleError(err)
		}

		if b.Core.logger.IsInfo() {
			b.Core.logger.Info("mount tuning of token_type successful", "path", path, "token_type", ttString)
		}
	}

	if rawVal, ok := data.GetOk("passthrough_request_headers"); ok {
		headers := rawVal.([]string)

		oldVal := mountEntry.Config.PassthroughRequestHeaders
		mountEntry.Config.PassthroughRequestHeaders = headers

		// Update the mount table
		var err error
		switch {
		case strings.HasPrefix(path, "auth/"):
			err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local)
		default:
			err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local)
		}
		if err != nil {
			mountEntry.Config.PassthroughRequestHeaders = oldVal
			return handleError(err)
		}

		mountEntry.SyncCache()

		if b.Core.logger.IsInfo() {
			b.Core.logger.Info("mount tuning of passthrough_request_headers successful", "path", path)
		}
	}

	if rawVal, ok := data.GetOk("allowed_response_headers"); ok {
		headers := rawVal.([]string)

		oldVal := mountEntry.Config.AllowedResponseHeaders
		mountEntry.Config.AllowedResponseHeaders = headers

		// Update the mount table
		var err error
		switch {
		case strings.HasPrefix(path, "auth/"):
			err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local)
		default:
			err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local)
		}
		if err != nil {
			mountEntry.Config.AllowedResponseHeaders = oldVal
			return handleError(err)
		}

		mountEntry.SyncCache()

		if b.Core.logger.IsInfo() {
			b.Core.logger.Info("mount tuning of allowed_response_headers successful", "path", path)
		}
	}

	var err error
	var resp *logical.Response
	var options map[string]string
	if optionsRaw, ok := data.GetOk("options"); ok {
		options = optionsRaw.(map[string]string)
	}

	if len(options) > 0 {
		b.Core.logger.Info("mount tuning of options", "path", path, "options", options)
		newOptions := make(map[string]string)
		var kvUpgraded bool

		// The version options should only apply to the KV mount, check that first
		if v, ok := options["version"]; ok {
			// Special case to make sure we can not disable versioning once it's
			// enabled. If the vkv backend suports downgrading this can be removed.
			meVersion, err := parseutil.ParseInt(mountEntry.Options["version"])
			if err != nil {
				return nil, errwrap.Wrapf("unable to parse mount entry: {{err}}", err)
			}
			optVersion, err := parseutil.ParseInt(v)
			if err != nil {
				return handleError(errwrap.Wrapf("unable to parse options: {{err}}", err))
			}

			// Only accept valid versions
			switch optVersion {
			case 1:
			case 2:
			default:
				return logical.ErrorResponse(fmt.Sprintf("invalid version provided: %d", optVersion)), logical.ErrInvalidRequest
			}

			if meVersion > optVersion {
				// Return early if version option asks for a downgrade
				return logical.ErrorResponse(fmt.Sprintf("cannot downgrade mount from version %d", meVersion)), logical.ErrInvalidRequest
			}
			if meVersion < optVersion {
				kvUpgraded = true
				resp = &logical.Response{}
				resp.AddWarning(fmt.Sprintf("Upgrading mount from version %d to version %d. This mount will be unavailable for a brief period and will resume service shortly.", meVersion, optVersion))
			}
		}

		// Upsert options value to a copy of the existing mountEntry's options
		for k, v := range mountEntry.Options {
			newOptions[k] = v
		}
		for k, v := range options {
			// If the value of the provided option is empty, delete the key We
			// special-case the version value here to guard against KV downgrades, but
			// this piece could potentially be refactored in the future to be non-KV
			// specific.
			if len(v) == 0 && k != "version" {
				delete(newOptions, k)
			} else {
				newOptions[k] = v
			}
		}

		// Update the mount table
		oldVal := mountEntry.Options
		mountEntry.Options = newOptions
		switch {
		case strings.HasPrefix(path, "auth/"):
			err = b.Core.persistAuth(ctx, b.Core.auth, &mountEntry.Local)
		default:
			err = b.Core.persistMounts(ctx, b.Core.mounts, &mountEntry.Local)
		}
		if err != nil {
			mountEntry.Options = oldVal
			return handleError(err)
		}

		// Reload the backend to kick off the upgrade process. It should only apply to KV backend so we
		// trigger based on the version logic above.
		if kvUpgraded {
			err = b.Core.reloadBackendCommon(ctx, mountEntry, strings.HasPrefix(path, credentialRoutePrefix))
			if err != nil {
				b.Core.logger.Error("mount tuning of options: could not reload backend", "error", err, "path", path, "options", options)
			}

		}
	}

	return resp, nil
}
1083760
func HandlerFunc(log func(message string, time time.Time, level LogLevel, call CallStack, context ContextMap) error) LogHandler {
	return remoteHandler(log)
}
170462
func (m *ServeMux) HandleFunc(method string, path string, h interface{}) {
	m.Handle(method, path, &handlerContainerImpl{
		handler: h,
		Context: background,
	})
}
315537
func (f EventHandlerFunc) HandleEvent(resp http.ResponseWriter, req *http.Request, event *Event) {
	f(resp, req, event)
}
133824
func (b *SystemBackend) handleRawWrite(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {
	path := data.Get("path").(string)

	// Prevent access of protected paths
	for _, p := range protectedPaths {
		if strings.HasPrefix(path, p) {
			err := fmt.Sprintf("cannot write '%s'", path)
			return logical.ErrorResponse(err), logical.ErrInvalidRequest
		}
	}

	value := data.Get("value").(string)
	entry := &logical.StorageEntry{
		Key:   path,
		Value: []byte(value),
	}
	if err := b.Core.barrier.Put(ctx, entry); err != nil {
		return logical.ErrorResponse(err.Error()), logical.ErrInvalidRequest
	}
	return nil, nil
}
15537
func (h HandlerFunc) Handle(data json.RawMessage, ctx *apex.Context) (interface{}, error) {
	event, record := new(Event), new(Record)

	if err := json.Unmarshal(data, record); err != nil {
		return nil, err
	}

	if err := decode(record, event); err != nil {
		return nil, err
	}

	if err := h(event, ctx); err != nil {
		return nil, err
	}

	return event, nil
}
522193
func (b *Bot) HandleFunc(cmd string, handler func(s Sender, m *irc.Message)) {
	b.handlers[cmd] = append(b.handlers[cmd], HandlerFunc(handler))
}
406420
func (conn *Conn) HandleFunc(name string, hf HandlerFunc) Remover {
	return conn.Handle(name, hf)
}
739916
func (ctx *Context) Writef(format string, a ...interface{}) (int, error) {
	return fmt.Fprintf(ctx, format, a...)
}
272355
func (s *ServeMux) HandleFunc(path string, handler func(http.ResponseWriter, *http.Request)) {
	s.Handle(path, http.HandlerFunc(handler))
}
873575
func (f HandshakeHeaderFunc) WriteTo(w io.Writer) (int64, error) {
	return f(w)
}