You are an expert in writing code in many different languages. Your goal is to perform code completion for the following code, keeping in mind the rest of the code and the file meta data.
    Metadata details:
    filename: handlers.go
    path of file: ./repos/juju/worker/controlsocket
    
    the code of the file until where you have to start completion: // Copyright 2023 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package controlsocket

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
	"github.com/juju/errors"
	"github.com/juju/names/v5"

	"github.com/juju/juju/core/permission"
	"github.com/juju/juju/environs/bootstrap"
	"github.com/juju/juju/state"
	stateerrors "github.com/juju/juju/state/errors"
)

const (
	// jujuMetricsUserPrefix defines the "namespace" in which this worker is
	// allowed to create/remove users.
	jujuMetricsUserPrefix = "juju-metrics-"

	// userCreator is the listed "creator" of metrics users in state.
	// This user CANNOT be a local user (it must have a domain), otherwise the
	// model addUser code will complain about the user not existing.
	userCreator = "controller@juju"
)

func (w *Worker) registerHandlers(r *mux.Router) {
	r.HandleFunc("/metrics-users", w.handleAddMetricsUser).
		Methods(http.MethodPost)
	r.HandleFunc("/metrics-users/{username}", w.handleRemoveMetricsUser).
		Methods(http.MethodDelete)
}

type addMetricsUserBody struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

func (w *Worker) handleAddMetricsUser(resp http.ResponseWriter, req *http.Request) {
	var parsedBody addMetricsUserBody
	defer req.Body.Close()
	err := json.NewDecoder(req.Body).Decode(&parsedBody)
	if errors.Is(err, io.EOF) {
		w.writeResponse(resp, http.StatusBadRequest, errorf("missing request body"))
		return
	} else if err != nil {
		w.writeResponse(resp, http.StatusBadRequest, errorf("request body is not valid JSON: %v", err))
		return
	}

	code, err := w.addMetricsUser(parsedBody.Username, parsedBody.Password)
	if err != nil {
		w.writeResponse(resp, code, errorf("%v", err))
		return
	}

	w.writeResponse(resp, code, infof("create
    
func (w *Worker) addMetricsUser(username, password string) (int, error) {
	err := validateMetricsUsername(username)
	if err != nil {
		return http.StatusBadRequest, err
	}

	if password == "" {
		return http.StatusBadRequest, errors.NotValidf("empty password")
	}

	user, err := w.config.State.AddUser(username, username, password, userCreator)
	cleanup := true
	// Error handling here is a bit subtle.
	switch {
	case errors.Is(err, errors.AlreadyExists):
		// Retrieve existing user
		user, err = w.config.State.User(names.NewUserTag(username))
		if err != nil {
			return http.StatusInternalServerError,
				fmt.Errorf("retrieving existing user %q: %v", username, err)
		}

		// We want this operation to be idempotent, but at the same time, this
		// worker shouldn't mess with users that have not been created by it.
		// So ensure the user is identical to what we would have created, and
		// otherwise error.
		if user.CreatedBy() != userCreator {
			return http.StatusConflict, errors.AlreadyExistsf("user %q (created by %q)", user.Name(), user.CreatedBy())
		}
		if !user.PasswordValid(password) {
			return http.StatusConflict, errors.AlreadyExistsf("user %q", user.Name())
		}

	case err == nil:
		// At this point, the operation is in a partially completed state - we've
		// added the user, but haven't granted them the correct model permissions.
		// If there is an error granting permissions, we should attempt to "rollback"
		// and remove the user again.
		defer func() {
			if cleanup == false {
				// Operation successful - nothing to clean up
				return
			}

			err := w.config.State.RemoveUser(user.UserTag())
			if err != nil {
				// Best we can do here is log an error.
				w.config.Logger.Warningf("add metrics user failed, but could not clean up user %q: %v",
					username, err)
			}
		}()

	default:
		return http.StatusInternalServerError, errors.Annotatef(err, "failed to create user %q: %v", username, err)
	}

	// Give the new user permission to access the metrics endpoint.
	var model model
	model, err = w.config.State.Model()
	if err != nil {
		return http.StatusInternalServerError, errors.Annotatef(err, "retrieving current model: %v", err)
	}

	_, err = model.AddUser(state.UserAccessSpec{
		User:      user.UserTag(),
		CreatedBy: names.NewUserTag(userCreator),
		Access:    permission.ReadAccess,
	})
	if err != nil && !errors.Is(err, errors.AlreadyExists) {
		return http.StatusInternalServerError, errors.Annotatef(err, "adding user %q to model %q: %v", username, bootstrap.ControllerModelName, err)
	}

	cleanup = false
	return http.StatusOK, nil
}