2016-10-17 4 views

答えて

56

http.ResponseWriter.WriteHeaderを使用してください。ドキュメントから:

WriteHeaderはステータスコードとともにHTTP応答ヘッダーを送信します。 WriteHeaderが明示的に呼び出されない場合、Writeへの最初の呼び出しは暗黙のWriteHeader(http.StatusOK)をトリガーします。したがって、WriteHeaderへの明示的な呼び出しは、主にエラーコードの送信に使用されます。

例:

func ServeHTTP(w http.ResponseWriter, r *http.Request) { 
    w.WriteHeader(http.StatusInternalServerError) 
    w.Write([]byte("500 - Something bad happened!")) 
} 
8
w.WriteHeader(http.StatusInternalServerError) 
w.WriteHeader(http.StatusForbidden) 

完全なリストWriteHeader(int)は別にhere

27

ます。たとえば、ヘルパーメソッドhttp.Errorを使用することができます。

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()とhttp.StatusText()メソッドはあなたの友人です

関連する問題