ANTICHAT

ANTICHAT (https://forum.antichat.xyz/index.php)
-   Общие вопросы программирования (https://forum.antichat.xyz/forumdisplay.php?f=206)
-   -   Go. Удаление поля структуры при отправке ответа (https://forum.antichat.xyz/showthread.php?t=1523995)

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)



Время: 09:46