How to set HTTP status code on http.ResponseWriter

后端 未结 3 1203
隐瞒了意图╮
隐瞒了意图╮ 2021-01-30 19:28

How do I set the HTTP status code on an http.ResponseWriter (e.g. to 500 or 403)?

I can see that requests normally have a status code of 200 attached to the

3条回答
  •  误落风尘
    2021-01-30 19:55

    Apart from WriteHeader(int) you can use the helper method http.Error, for example:

    func yourFuncHandler(w http.ResponseWriter, r *http.Request) {
    
        http.Error(w, "my own error message", http.StatusForbidden)
    
        // or using the default message error
    
        http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
    }
    

    http.Error() and http.StatusText() methods are your friends

提交回复
热议问题