更新地图中的键,同时遍历该地图

I want to update the key from one name to another using URL params. I have the code, but the output is incorrect. See below.

This is the map

var data map[string][]string

The PUT method for the function im calling

r.HandleFunc("/updatekey/{key}/{newkey}", handleUpdateKey).Methods("PUT")

The handleUpdateKey func, which is noted up explaining exactly what it's doing.

func handleUpdateKey(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)

k := params["key"] //get url params
nk := params["newkey"]

s := make([]string, len(data[k])) //create slice of string to store map variables
for i := range data {             //range over the data map
    fmt.Fprintf(w, i)
    if k != i { //check if no keys exist with URL key param
        fmt.Fprintf(w, "That KEY doesn't exist in memory")
        break //kill the loop
    } else { //if there is a key the same as the key param
        for _, values := range data[i] { //loop over the slice of string (values in that KEY)
            s = append(s, values) //append all those items to the slice of string
        }

        delete(data, k) //delete the old key

        for _, svalues := range s { //loop over the slice of string we created earlier
            data[nk] = append(data[nk], svalues) //append the items within the slice of string, to the new key... replicating the old key, with a new key name
        }
    }
}
}

The below should assign all the values of that KEY to a slice of string, which we later iterate over and add to the new KEY. This works, however, the output is as below which is clearly incorrect

KEY: catt: VALUE: 
KEY: catt: VALUE: 
KEY: catt: VALUE: zeus
KEY: catt: VALUE: xena

OLD OUTPUT:

KEY: dog: VALUE: zeus
KEY: dog: VALUE: xena

CORRECT NEW OUTPUT:

KEY: catt: VALUE: zeus
KEY: catt: VALUE: xena

In most languages, altering a structure you're iterating over will cause strange things to happen. Particularly maps. You have to find another way.

Fortunately there's no need to iterate at all. Your loop is just one big if/else statement. If the key matches, do something. If it doesn't, do something else. Since this is a map, there's no need to search for the key using iteration, it can be looked up directly. There's also no need for all that laborious looping just to copy a map value.

if val, ok := data[k]; ok {
    // Copy the value
    data[nk] = val
    // Delete the old key
    delete(data, k)
} else {
    fmt.Fprintf(w, "The key %v doesn't exist", k)
}

Finally, avoid using globals in functions. It makes it difficult to understand what effect a function has on the program if it can change globals. data should be passed in to the function to make it clear.

func handleUpdateKey(w http.ResponseWriter, r *http.Request, data map[string][]string)