PDA

Просмотр полной версии : Go. Удаление поля структуры при отправке ответа


chapo
02.11.2024, 12:55
Хай. Есть структура

Код:






type Item struct {
Name string `json:"name"`
Author string `json:"author"`
SecretKey string `json:"secretKey"`
Model uint16 `json:"model"`
Bone uint8 `json:"bone"`
Position [3]float64 `json:"position"`
Rotation [3]float64 `json:"rotation"`
Scale [3]float64 `json:"scale"`
}




так же есть

Go:






var items []Item




Сервер отправляет items в JSON формате. Как при отправке ответа удалить/изменить все поля "SecretKey" в срезе?

Код:






func listRequestHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
jsonString, err := json.Marshal(items)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(string(jsonString)))
}

chapo
03.11.2024, 15:59
Решил. Обошелся без удаления

Go:






userItems := make([]Item, len(items))
copy(userItems, items)
for index := range userItems {
userItems[index].SecretKey = "*"
}
jsonString, err := json.Marshal(userItems)