我想使用 URL 参数将密钥从一个名称更新为另一个名称。我有代码,但输出不正确。见下文。
这是地图
var data map[string][]string
调用函数的 PUT 方法
r.HandleFunc("/updatekey/{key}/{newkey}", handleUpdateKey).Methods("PUT")
handleUpdateKey 函数,它被记录下来,准确地解释了它在做什么。
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
}
}
}
}
下面应该将该 KEY 的所有值分配给一段字符串,我们稍后会对其进行迭代并将其添加到新的 KEY 中。这有效,但是,输出如下,这显然是不正确的
KEY: catt: VALUE:
KEY: catt: VALUE:
KEY: catt: VALUE: zeus
KEY: catt: VALUE: xena
旧输出:
KEY: dog: VALUE: zeus
KEY: dog: VALUE: xena
正确的新输出:
KEY: catt: VALUE: zeus
KEY: catt: VALUE: xena
潇潇雨雨
相关分类