概述
golang的net/http包提供了状态代码常量,可以用来返回不同的状态代码--golang.org/src/net/htt…。
HTTP 401状态代码是由以下常量定义的。
http.StatusUnauthorized
在这篇文章中,我们还将看到如何在返回401(未经授权)状态代码的同时返回一个JSON体。
程序
下面是同样的程序
package main
import (
"encoding/json"
"log"
"net/http"
)
func main() {
handler := http.HandlerFunc(handleRequest)
http.Handle("/example", handler)
http.ListenAndServe(":8080", nil)
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
w.Header().Set("Content-Type", "application/json")
resp := make(map[string]string)
resp["message"] = "Unauthorized"
jsonResp, err := json.Marshal(resp)
if err != nil {
log.Fatalf("Error happened in JSON marshal. Err: %s", err)
}
w.Write(jsonResp)
return
}
这里我们使用WriteHeader函数来指定401 http状态代码,并使用Write函数来返回响应体。
{"message":"Unauthorized"}
运行上述程序。它将在你的本地机器上启动一个8080端口的服务器。现在对服务器进行下面的curl调用
curl -v -X POST http://localhost:8080/example
下面将是输出结果
* Connected to localhost (::1) port 8080 (#0)
> POST /example HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
>
< HTTP/1.1 401 Unauthorized
< Date: Sat, 10 Jul 2021 08:19:52 GMT
< Content-Length: 26
< Content-Type: text/plain; charset=utf-8
<
* Connection #0 to host localhost left intact
{"message":"Unauthorized"}
你可以从输出中看到,它将正确地返回401状态代码和正文。
你也可以直接把401传给WriteHeader函数来发送401响应。
w.WriteHeader(401)
这也能正确工作。试一试吧。