如何在http.ResponseWriter上设置HTTP状态代码

时间:2016-10-17 22:37:36

标签: go

如何在http.ResponseWriter上设置HTTP状态代码(例如,设置为500或403)?

我可以看到请求通常附有200的状态代码。

3 个答案:

答案 0 :(得分:116)

使用http.ResponseWriter.WriteHeader。来自文档:

  

WriteHeader发送带有状态代码的HTTP响应头。如果未显式调用WriteHeader,则第一次调用Write将触发隐式WriteHeader(http.StatusOK)。因此,对WriteHeader的显式调用主要用于发送错误代码。

示例:

num = 1;
while(True): #keeps going until it finds the number
    b = True #remains true as long as it is divisible by div
    for div in range(1,21):
        if not (num % div == 0):
            b = False #number was not divisible, therefore b is now false
            num += 1
            break
    if(b): #b means num was divisible by all numbers.
        break
print(num)

答案 1 :(得分:55)

WriteHeader(int)外,您可以使用辅助方法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()方法是你的朋友

答案 2 :(得分:20)

w.WriteHeader(http.StatusInternalServerError)
w.WriteHeader(http.StatusForbidden)

完整列表here