Как выстовить код ошибки в http.ResponseWriter?

Как выставить код ошибки в http.ResponseWriter?


Ответы (1 шт):

Автор решения: Senior Pomidor

пример


func JSONError(httpcode int, code, msg string, w http.ResponseWriter) {
    type Error struct {
        Code    *string `json:"code,omitempty"`
        Message *string `json:"message,omitempty"`
    }

    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    w.Header().Set("X-Content-Type-Options", "nosniff")
    w.WriteHeader(httpcode)
    json.NewEncoder(w).Encode(
        Error{
            Code:    &code,
            Message: &msg,
        },
    )
}

внутри хэндлера можно использовать как

    err := doStuff()
    if err != nil {
        JSONError(500, "custom error code number", "doStuff error", w)
        return
    }
→ Ссылка