반응형
How to set HTTP status code on http.ResponseWriter
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 them.
Use http.ResponseWriter.WriteHeader
. From the documentation:
WriteHeader sends an HTTP response header with status code. If WriteHeader is not called explicitly, the first call to Write will trigger an implicit WriteHeader(http.StatusOK). Thus explicit calls to WriteHeader are mainly used to send error codes.
Example:
func ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Something bad happened!"))
}
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
w.WriteHeader(http.StatusInternalServerError)
w.WriteHeader(http.StatusForbidden)
full list here
참고URL : https://stackoverflow.com/questions/40096750/how-to-set-http-status-code-on-http-responsewriter
반응형
'Programing' 카테고리의 다른 글
변수 선언은 비용이 많이 듭니까? (0) | 2020.10.23 |
---|---|
기호를 찾을 수 없음 : kUTTypeImage (0) | 2020.10.23 |
String의 hashCode ()가 0을 캐시하지 않는 이유는 무엇입니까? (0) | 2020.10.22 |
ʻipython` 탭 자동 완성이 가져온 모듈에서 작동하지 않습니다. (0) | 2020.10.22 |
PHP : 파일 생성 날짜는 어떻게 알 수 있습니까? (0) | 2020.10.22 |